Share to: share facebook share twitter share wa share telegram print page

Stack overflow

In software, a stack overflow occurs if the call stack pointer exceeds the stack bound. The call stack may consist of a limited amount of address space, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash.[1]

Causes

Infinite recursion

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.[2]

An example of infinite recursion in C.

int foo() 
{
     return foo();
}

The function foo, when it is invoked, continues to invoke itself, allocating additional space on the stack each time, until the stack overflows resulting in a segmentation fault.[2] However, some compilers implement tail-call optimization, allowing infinite recursion of a specific sort—tail recursion—to occur without stack overflow. This works because tail-recursion calls do not take up additional stack space.[3]

Some C compiler options will effectively enable tail-call optimization; for example, compiling the above simple program using gcc with -O1 will result in a segmentation fault, but not when using -O2 or -O3, since these optimization levels imply the -foptimize-sibling-calls compiler option.[4] Other languages, such as Scheme, require all implementations to include tail-recursion as part of the language standard.[5]

Very deep recursion

A recursive function that terminates in theory but causes a call stack buffer overflow in practice can be fixed by transforming the recursion into a loop and storing the function arguments in an explicit stack (rather than the implicit use of the call stack). This is always possible because the class of primitive recursive functions is equivalent to the class of LOOP computable functions. Consider this example in C++-like pseudocode:

void function (argument) 
{
  if (condition)
    function (argument.next);

}
stack.push(argument);
while (!stack.empty())
{
  argument = stack.pop();
  if (condition)
    stack.push(argument.next);
}

A primitive recursive function like the one on the left side can always be transformed into a loop like on the right side.

A function like the example above on the left would not be a problem in an environment supporting tail-call optimization; however, it is still possible to create a recursive function that may result in a stack overflow in these languages. Consider the example below of two simple integer exponentiation functions.

int pow(int base, int exp) {
    if (exp > 0)
        return base * pow(base, exp - 1);
    else
        return 1;
}
int pow(int base, int exp) {
    return pow_accum(base, exp, 1);
}

int pow_accum(int base, int exp, int accum) {
    if (exp > 0)
        return pow_accum(base, exp - 1, accum * base);
    else
        return accum;
}

Both pow(base, exp) functions above compute an equivalent result, however, the one on the left is prone to causing a stack overflow because tail-call optimization is not possible for this function. During execution, the stack for these functions will look like this:

pow(5, 4)
5 * pow(5, 3)
5 * (5 * pow(5, 2))
5 * (5 * (5 * pow(5, 1)))
5 * (5 * (5 * (5 * pow(5, 0))))
5 * (5 * (5 * (5 * 1)))
625
pow(5, 4)
pow_accum(5, 4, 1)
pow_accum(5, 3, 5)
pow_accum(5, 2, 25)
pow_accum(5, 1, 125)
pow_accum(5, 0, 625)
625

Notice that the function on the left must store in its stack exp number of integers, which will be multiplied when the recursion terminates and the function returns 1. In contrast, the function at the right must only store 3 integers at any time, and computes an intermediary result which is passed to its following invocation. As no other information outside of the current function invocation must be stored, a tail-recursion optimizer can "drop" the prior stack frames, eliminating the possibility of a stack overflow.

Very large stack variables

The other major cause of a stack overflow results from an attempt to allocate more memory on the stack than will fit, for example by creating local array variables that are too large. For this reason some authors recommend that arrays larger than a few kilobytes should be allocated dynamically instead of as a local variable.[6]

An example of a very large stack variable in C:

int foo() 
{
     double x[1048576];
}

On a C implementation with 8 byte double-precision floats, the declared array consumes 8 megabytes of data; if this is more memory than is available on the stack (as set by thread creation parameters or operating system limits), a stack overflow will occur.

Constrained environment

Stack overflows are made worse by anything that reduces the effective stack size of a given program. For example, the same program being run without multiple threads might work fine, but as soon as multi-threading is enabled the program will crash. This is because most programs with threads have less stack space per thread than a program with no threading support. Because kernels are generally multi-threaded, people new to kernel development are usually discouraged from using recursive algorithms or large stack buffers.[7]

See also

References

  1. ^ Burley, James Craig (1991-06-01). "Using and Porting GNU Fortran". Archived from the original on 2012-02-06.
  2. ^ a b What is the difference between a segmentation fault and a stack overflow? Archived 2021-09-13 at the Wayback Machine at Stack Overflow
  3. ^ "An Introduction to Scheme and its Implementation". 1997-02-19. Archived from the original on 2007-08-10.
  4. ^ "Using the GNU Compiler Collection (GCC): Optimize Options". Archived from the original on 2017-08-20. Retrieved 2017-08-20.
  5. ^ Richard Kelsey; William Clinger; Jonathan Rees; et al. (August 1998). "Revised5 Report on the Algorithmic Language Scheme". Higher-Order and Symbolic Computation. 11 (1): 7–105. doi:10.1023/A:1010051815785. S2CID 14069423. Archived from the original on 2007-01-05. Retrieved 2012-08-09.
  6. ^ Feldman, Howard (2005-11-23). "Modern Memory Management, Part 2". Archived from the original on 2012-09-20. Retrieved 2007-08-14.
  7. ^ "Kernel Programming Guide: Performance and Stability Tips". Apple Inc. 2014-05-02. Archived from the original on 2014-05-03. Retrieved 2014-05-02.

Read other articles:

Piet Bekaert (Vichte, 8 mei 1939 - Deurle, 7 juli 2000) was een Belgisch kunstenaar. Portret van Piet Bekaert door Willy Bosschem, 1985 Jeugd en opleiding Piet Bekaert studeerde aan de RUG, de Koninklijke Academie voor Schone Kunsten te Gent en daarna aan de Académie Julian te Parijs. Toen hij 29 was vertrok hij naar New York en werd Master in Interior Design aan het Pratt Institute. Hij werkte bij Bauhaus-architect Edward Durell Stone mee aan prestigieuze bouwprojecten. Al voor zijn vertrek...

смт Новосвітлівка Країна  Україна Область Луганська область Район Луганський район Громада Молодогвардійська міська громада Код КАТОТТГ: Основні дані Засноване 1860 Площа  км² Населення ▲3755 (01.01.2011)[1] Поштовий індекс 94456 Телефонний код +380 6435 Географічні координат

Tributil fosfat Model pengisian ruang dari Tributil fosfat Model bola dan tongkat dari Tributil fosfat Penanda Nomor CAS 126-73-8 Y6131-90-4 (trihydrate) N Model 3D (JSmol) Gambar interaktif 3DMet {{{3DMet}}} ChEBI CHEBI:35019 Y ChemSpider 29090 Y Nomor EC KEGG C14439 Y PubChem CID 31357 Nomor RTECS {{{value}}} UNII 95UAS8YAF5 Y CompTox Dashboard (EPA) DTXSID3021986 InChI InChI=1S/C12H27O4P/c1-4-7-10-14-17(13,15-11-8-5-2)16-12-9-6-3/h4-12H2,1-3H3 YKey:&...

Haus Marschnerstraße 12 Die Villenkolonie Pasing II ist eine Einfamilienhauskolonie in München-Pasing. Sie wurde nach dem Modell einer Gartenstadt im Anschluss an die Villenkolonie Pasing I errichtet. Inhaltsverzeichnis 1 Geschichte 2 Straßen 3 Anmerkungen 4 Literatur 5 Weblinks Geschichte Auch die Idee zur Villenkolonie Pasing II westlich der Würm kam von August Exter, jedoch scheiterte er an der Planung. Im Jahr 1897 gab Exter sein Baugeschäft[1] auf und zog sich schrittweise v...

American football player (born 1995) American football player Myles GarrettGarrett with the Browns in 2021No. 95 – Cleveland BrownsPosition:Defensive endPersonal informationBorn: (1995-12-29) December 29, 1995 (age 27)Arlington, Texas, U.S.Height:6 ft 4 in (1.93 m)Weight:272 lb (123 kg)Career informationHigh school:Martin (Arlington, Texas)College:Texas A&M (2014–2016)NFL Draft:2017 / Round: 1 / Pick: 1Career history Cleveland Browns (...

Development of insects from an ancestral crustacean and their subsequent radiation Evolution has produced astonishing variety of appendages in insects, such as these antennae. The most recent understanding of the evolution of insects is based on studies of the following branches of science: molecular biology, insect morphology, paleontology, insect taxonomy, evolution, embryology, bioinformatics and scientific computing. It is estimated that the class of insects originated on Earth about 480 ...

2013年象牙海岸踩踏慘劇烏弗埃-博瓦尼球場(英语:Stade Félix Houphouët-Boigny)日期2013年1月1日,​10年前​(2013-01-01)地点科特迪瓦阿比讓座標5°19′41.7″N 4°1′6.3″W / 5.328250°N 4.018417°W / 5.328250; -4.018417坐标:5°19′41.7″N 4°1′6.3″W / 5.328250°N 4.018417°W / 5.328250; -4.018417起因人踩人死亡61受伤200+ 2013年科特迪瓦人踩人慘劇於2013年元旦...

List of events ← 1973 1972 1971 1974 in Pakistan → 1975 1976 1977 Decades: 1950s 1960s 1970s 1980s 1990s See also: History of Pakistan List of years in Pakistan Timeline of Pakistani history Events from the year 1974 in Pakistan. Incumbents Federal government President: Fazal Ilahi Chaudhry Prime Minister: Zulfikar Ali Bhutto Chief Justice: Hamoodur Rahman Governors Governor of Balochistan: Nawab Akbar Khan Bugti (until 2 January); Ahmad Yar Khan (starting 2 January) Governor of K...

Країни, які мають посольство в Німеччині. Нижче наведено список дипломатичних місій в Німеччині. Федеративна Республіка Німеччина має дипломатичні відносини із 195-ма країнами світу, 193 з яких є членами ООН (іншими двома є Ватикан та Косово). На даний момент 159 держав мають ...

Untuk mantan Menteri Negara Urusan Pangan/Kepala Badan Urusan Logistik (Bulog) Republik Indonesia periode tahun 1995 sampai 1998, lihat Beddu Amang. Biografi ini tidak memiliki sumber tepercaya sehingga isinya tidak dapat dipastikan. Bantu memperbaiki artikel ini dengan menambahkan sumber tepercaya. Materi kontroversial atau trivial yang sumbernya tidak memadai atau tidak bisa dipercaya harus segera dihapus.Cari sumber: Bedu – berita · surat kabar · buku · c...

Internal shell of cirrate octopuses Dorsal (left) and ventral aspects of a mature female Grimpoteuthis innominata (73 mm ML). Cirrate octopuses possess a well-developed internal shell that supports their muscular swimming fins. This is in contrast to the more familiar, finless, incirrate octopuses, in which the shell remnant is either present as a pair of stylets or absent altogether.[1] The cirrate shell is quite unlike that of any other living cephalopod group and has its own d...

American actor, writer, and comedian Chris PowellPowell in 2017 on The 85 South Comedy ShowBornChristopher PowellDetroit, MichiganOther namesComedian CPAlma materMichigan State UniversityOccupation(s)Actor, comedianYears active2010—presentKnown forDetroiters, Love Life Christopher Powell, also known as Comedian CP, is an American actor, writer, and comedian. He appeared on Empire, Detroiters, All Def Comedy, and season two of HBO Max's Love Life. Life and career Powell w...

Lambang Nugini BelandaDetailDigunakan sejak1961[1]PerisaiAzure, enam palet Argent, di atas kepala Gules a Mullet dengan lima poin ArgentPenopangDua Burung CendrawasihMottoSetia, Djudjur, Mesra (Indonesia) Lambang Nugini Belanda adalah simbol nasional pada masa dekolonisasi Belanda dan sebelum Papua masuk ke dalam wilayah Indonesia. Desain perisai pada lambang ini berbentuk Bendera Bintang Kejora. Perisai itu dikelilingi oleh dua burung Cenderawasih yang dikelilingi oleh bunga lokal da...

2010 studio album by Fat JoeThe Darkside Vol. 1Studio album by Fat JoeReleasedJuly 27, 2010[1]Recorded2009–2010Genre Hip hop hardcore hip hop[2] Length49:11LabelTerror Squad, E1ProducerCool & Dre (also exec.), Macho TS (exec.), Zeferiah (also exec.), DJ Premier, Dope Boyz, I.L.O., Infamous, Just Blaze, Laurent Slick Cohen, Raw Uncut, Scram Jones, Scoop DeVille, StreetrunnerFat Joe chronology Jealous Ones Still Envy 2 (J.O.S.E. 2)(2009) The Darkside Vol. 1(2010) T...

1912 novel by A. E. W. Mason The Turnstile AuthorA. E. W. MasonCountryEngland, ArgentinaLanguageEnglishPublisherHodder & StoughtonPublication date1912[1]Media typePrintPages344[1] The Turnstile is a 1912 political novel by the English author A. E. W. Mason. The novel's fictional hero was based party upon the author's own experiences as a Member of parliament, and partly upon his friend Robert Falcon Scott, who at that time had yet to start out on his ill-fated expedit...

Species of fish Double-lined mackerel Drawing of Grammatorcynus bilineatus Conservation status Least Concern (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Actinopterygii Order: Scombriformes Family: Scombridae Genus: Grammatorcynus Species: G. bilineatus Binomial name Grammatorcynus bilineatus(Rüppell, 1836) Synonyms Thynnus bilineatus Rüppell, 1836 Nesogrammus piersoni Evermann and Seale, 1907 The double-lined mackerel...

List of events ← 1980 1979 1978 1977 1976 1981 in Scotland → 1982 1983 1984 1985 1986 Centuries: 18th 19th 20th 21st Decades: 1960s 1970s 1980s 1990s 2000s See also:List of years in ScotlandTimeline of Scottish history1981 in: The UK • Wales • ElsewhereScottish football: 1980–81 • 1981–821981 in Scottish television Events from the year 1981 in Scotland. Incumbents Further information: Politics of Scotland and Order of precedence in Scotland Secretary of State...

British politician (1877–1960) The Right HonourableThe Lord Haden-GuestMCMember of Parliament for Islington NorthIn office13 October 1937 – 3 February 1950Preceded byAlbert GoodmanSucceeded byMoelwyn HughesMember of Parliament for Southwark NorthIn office6 December 1923 – 1927Preceded byEdward StraussSucceeded byEdward Strauss Personal detailsBorn(1877-03-10)10 March 1877Oldham, Lancashire, EnglandDied20 August 1960(1960-08-20) (aged 83)Political partyLabourAlma m...

Malaysian politician In this Malay name, there is no family name. The name Asari is a patronymic, and the person should be referred to by the given name, Abdul Rashid. The Arabic-derived word bin or binti/binte, if used, means 'son of' or 'daughter of', respectively. Yang Berhormat DatukAbdul Rashid AsariPSD SMS MLAعبدالرشيد بن عصريMember of the Selangor State Executive Council (Culture, Tourism, Malay Civilisation and Heritage)In office14 May 2018 – 5 March 2020Mona...

2011 Russian filmAll InclusiveDirected byEdouard RadzyukevichWritten byAlexander MalenkovProduced byYuri MinzyanovVladislav RyashinStarringMikhail Bespalov Marina Aleksandrova Nonna Grishayeva Roman Madyanov Fyodor Dobronravov CinematographyDenis PanovMusic byArkady UkupnikProductioncompanyParadiseRelease date June 9, 2011 (2011-06-09) Running time93 minutesCountryRussiaLanguageRussianBox office$6 103 256[1] All Inclusive (Russian: All inclusive, или Всё вклю...

Kembali kehalaman sebelumnya