Adventures with _chkstk

_chkstk Routine is a helper routine for the C compiler. For x86 compilers, _chkstk Routine is called when the local variables exceed 4K bytes; for x64 compilers it is 8K.
That's all that you get from _chkstk()'s MSDN web page. Nothing more...


A process starts with a fixed stack space. The top of a stack is pointed to by the Extended Stack Pointer (ESP) register and this is a decrementing pointer. Every function call results in a stack created for the function inside this Process Stack. Every thread function has its own stack. The stack is a downward growing array. The default stack reservation size is 1 MB and the heap's size theoretically increases to a limit of 4 GB on 32bits operation systems. See more information here.

Every thread under Windows has its own block of contiguous memory, and while function calls are made, the stack pointer is increasing and decreasing. In contrast, a different thread within the same process might get a different block of contiguous memory – its own stack. When a context switch occurs, the current thread’s ESP (along with the IP and other registers) are saved in the thread’s context structure, and restored when the thread is activated the next time.

In order to specify a different default stack reservation size for all threads and fibers, use the STACKSIZE statement in the module definition (.def) file. To change the initially committed stack space, use the dwStackSize parameter of the CreateThread, CreateRemoteThread, or CreateFiber function.
Most stack problems occur in overflows of existing stacks, as their sizes are fixed and they cannot be expanded.

_chkstk() increases the stack when needed by committing some of the pages previously reserved for the stack. If there is no more physical memory available for committed pages, _chkstk fails. When you enter a function (VC++ with the stack checking enabled), it will call the _chkstk located in CHKSTK.ASM. This function does a stack page probing and causes the necessary pages of memory to be allocated using the guard page scheme, if possible. In this function, it is stated that when it encounters _XCPT_GUARD_PAGE_VIOLATION, the OS will attempt to allocate another guarded page and if it encounters _XCPT_UNABLE_TO_GROW_STACK then it’s a stack overflow error. When _XCPT_UNABLE_TO_GROW_STACK is encountered, the stack is not yet set up properly; it will not call the catch because calling it will use invalid stack variables, which will again cause another exception.

Case – Too Many or Too Big Variables on Stack

As I said above, the function stack size is 1 MB. If you miss that and you're trying to define and use an array internally like this:

int arr[4000][200];

when you compile with VC++ compiler in debug mode, you will have a big surprise: the application crashes on _chkstk() at the moment the _chkstk() tries to create a new memory page on stack and fails.

Call Stack
Figure 1: Call Stack

The output window shows the next message:

First-chance exception at 0x004116e7 in testApp.exe: 0xC00000FD: Stack overflow.
Unhandled exception at 0x004116e7 in testApp.exe: 0xC00000FD: Stack overflow.

This happens because the 1MB limit is overloaded even on a win32 OS: 4000*200*4 = 3.2MB (approx.). It's the same story if you define many local variables and their stack usage overloads the 1MB limit. If you really need this big array then use heap to avoid this crash.

int **arr = new int*[4000];
for(int i=0; i<4000; ++i) {
	arr[i] = new int[200];
// and finaly don't forget to delete
for(int i=0;i<4000; ++i) {
	delete[] arr[i];
delete[] arr;

Case – Recursive Functions

If you have an infinite recursion then you will gate same stack overflow error and the application crashes in _chkstk.asm. Recursive function is outside the scope of this article. Here is a good example of what happens with recursive functions.
The solution is to avoid using recursive functions as much as possible and try to implement an iterative function.

Case – Stack Corruption

I started looking over _chkstk() implementation the moment I got a few bugs with crashes that had similar details. I had to analyze some .dump files and solve a few bugs that contained a call stack with _chkstk() on top. Most of the .dump files call stack contained a second similar thing: the call of a thread function (so called ThreadFoo()) that was running in a threads pool. I started to research why _chkstk() failed and my first track was to debug the stack overflows. I followed a MSDN debugging tutorial and unfortunately I didn't find anything strange. I checked to see if the local stack variables were filling the ThreadFoo() function’s stack and they did not.

A new study of ThreadFoo() function followed, in order to detect internal function calls that can fail in some circumstances. I checked some of the trace function calls in great detail. Those trace functions where defined in an external debug class and each time a new trace file was added it used an internal buffer (TCHAR szBuff[2048] = _T(“”);). The writing of this buffer was done using: swprintf(). As we know, this function is unsafe and is not recommended. As long as the content of these trace lines was dynamically built (in some cases those lines may contain dynamically built SQL queries that fail) then the length of these trace lines could be higher than 2048 bytes; then guess what, a stack corruption appears! UPS! The stack pointer will be corrupted (the classic stack overflow case).

So I have implemented and used the following macros:

#if defined(UNICODE) || defined(_UNICODE)  
#define usprintf(x, ...) \
   _snwprintf(x, _countof(x)-1, ##__VA_ARGS__); \
   x[_countof(x)-1] = 0
#define usprintf(x, ...) \
   _snprintf(x, _countof(x)-1, ##__VA_ARGS__); \
   x[_countof(x)-1] = 0

Now, if we use the safe macro, we will have no issues.

int x = 23;
TCHAR szMsg[2048] = {0};
usprintf(szMsg, _T("Error: %d"), x);

Another safe way is to allocate the buffer in the heap. However, in some cases, stack arrays may be preferred for performance reasons. After that was fixed I met with no other stack corruptions in ThreadFoo() or other code areas. Even if the top of the call stack was _chkstk() this was not the function that failed. The error appeared because of that stack corruption and _chkstk() has just detected.


If your code produces a stack overflow, then you have to rethink your design in the right away:

  • If you see _chkstk() on the top of call stack, check if you have no stack corruptions - stack overflow
  • Don't try to manipulate the stack by yourself. The default 1MB stack size is basically enough
  • Allocate dynamically if you're using big arrays
  • If you have recursive functions producing a stack overflow, re-write them using loops (a tip: it is a proven fact that any recursive functions can be programmed non-recursive)


About the Author

Silviu-Marius Ardelean

Silviu Ardelean is a software developer working for an American-based company. His main focus is on building C++ applications for Windows and Unix/Linux operating systems. Personal web log:

Related Articles


  • Lisseur ghd pas cher rend une femme plus belle en Norvège

    Posted by ketrqb580 on 07/16/2013 05:36am

    Maintenant, avec tension universelle pour une performance optimale partout dans le monde que vous êtes deg.Hvilemodus est une configuration de sécurité intégré qui vous donne la tranquillité d'esprit, car il s'éteint automatiquement technologie numérique av.Unik signifie que la température est contrôlée automatiquement encore plus rapide pour un meilleur style. New rounder baril de sorte qu'il est facile de créer des boucles parfaites, vagues ou chiquenaudes, ainsi que les supprimer. [url=]ghd pas cher[/url] GHD droit tige conteneur livfullheten et lambeaux de cheveux Farget. Près de la rivière pour s'assurer que la chaleur est répartie uniformément, ne devient jamais Hoy, reduserer La fargebevaringsteknologi unique avec IONTEC décoloration av Fargen en stylisme de 70% * et rend le Fargen obtient appareils de coiffage beaucoup plus glansfull.GHD ne fait pas ditt de cheveux terne et sec. Moi, sur IMot: ils empêchent fuktighetstap de style par y infliger ditt de cheveux satengioner unique! Ces ladde négatif ionène célébrations segment à la chevelure ladde positif ditt et reduserer sec, krusete cheveux et tiltrekker fuktighetspartikler de Lufta et leur envoyer votre le Trenger de cheveux le plus. [url=]ghd lisseur pas cher[/url] Lorsque le mot settes bon marché dans le même théorème comme Journée Good Hair (GHD) GHD est le mot faux normalement pas si loin unna. Tout Dessverre qui a marqué GHD et semble trop beau pour être y intéressant de prix, normalement. Vous pouvez être désespérée pour GHD droit tige merke, mais vous devriez envisager d'autres rubans de nom aussi, car il est beaucoup plus sur le marché qui va donner deg le même vétérinaire results.I qu'il est souvent coutumier aux consommateurs un loquet en utsalgspris que le temps passe. La couche gjentatt de tendance avec les lecteurs DVD et autres appareils électroniques. C'est beaucoup moins cher de leur offrir une solution fiable sur le marché, c'est juste un notre web av magasiner.

  • dresses2us

    Posted by dresses2us on 06/17/2013 08:31pm

    They're unaware of the truth that it is very much possible to find wedding gowns at reasonable prices at online retailers.Some handy hints take presctiption this website to help you optimize the price of purchasing jewelry, combined with the effo . I have bright maxi skirts which, when combined with a gentle curly blow dry, a felt hat, and perhaps a gold belt, could definitely nod to the trend; especially when strapless prom dresses just purchased a felt hat.Saviola foi o artilheiro e considerado o melhor jogador do Mundial.Then without thinking Gurus to take her photo and gave her this address, she's very modest too. Once empire waist prom dresses have reached a contract, maybe you could be more mature.Feeling confident with your image is part of feeling beautiful.Even though it might seem easy, you really need to educate yourself on how Internet mark .The ablaze can point at any ambition in the ambit of 10m to 10000m, that can be used it for pointing at blackboards, video monitors, photos and so on.The Internet is the other way which will help you buy these dresses at reasonable prices.Some added blush frequencies are 473nm dejected, 650nm red, 594nm chicken, and 405nm amethyst.Book in advance though because they become unattainable quickly. You will find a bridal shop on your next trip to Sin City or ask people around you for recommendations.You can just go online and pick you dress anytime you want to.We'd plenty of funny challenges and competitions throughout the day and that i won best dressed.If Prada sends it down the runway, you know it hot.They feature the finest assortment of designer Roycal Blue Strapless Monoclinal Flexures 2011 BridesmaidDress from leading other assortment can be to pair the short cocktail attire receiving an incredible offer of fancy jewelry.They then "attempt" to copy the designer gown.I ride my bike in dresses. when ever they'll be open to get has not yet been announced. buy prom dresses any change meet up.Depending on a few different factors, ALT text may be a good place for all those misspellings mentioned in 6.She knows it coming, and is happy to agree without hardware at hand.Drop the appetizers from $9 to $3 and you simply saved $900 during cocktail hour($6 per person X 150 persons).. 4. What do you think will happen to your blog in 2008.Additionally, you will look good in a lace jacket overlay.People on street style sites should smile like this more walked in you turned the corner and were faced with Dorothy Perkins first.Scientific studies report that music students possess more life skills that provide them an advantage over their peers.His content is very helpful to find out the best wedding gowns to create your look stand out and beautiful.You may also choose plain colors or even a goth motif.voice therefore it flows perfectly.If you are considering buying a gold ring you need to check the weight from the ring.These dresses can also be found online.Over the past few years Korean fashion has relocated from what things can ideal be termed a cottage industry to taking its location like a real force in .Request suggestions and opinions from people you can rely on, just like a sister or perhaps a friend.We wish them a contented life together.You may wish to rent an area inside a classy hotel and revel in a ceremony to assert your ex and intentions.

  • GHD jern beundrere vokser i antall og er forventet Ã¥ fortsette Ã¥ øke

    Posted by pletcherxsm on 06/14/2013 08:52am

    [url=]ghd rettetang norge[/url] Klemme en del av hår og gradvis krøller seg mot toppen. Hvis denne fremgangsmåten ikke gir deg den nødvendige effekten, må du bruke en annen metode; Bruk en fleksibel hårspray på en liten del av håret ditt før du setter hair rette jern om en tomme eller slik fra hodebunnen, og deretter få det ned mot slutten hår; håret krøller seg akkurat som du ville en båndet ved hjelp av et par saks. [url=]Rettetang ghd[/url] Utrolig GHD (god hår dag) med nesten ingen annonsering, oppnådd ikonisk status i en utrolig kort tid, tjene priser venstre, høyre og sentrum og alle disse kredittene går til en ex-frisør for en topp salong Robert Powls, mannen som skjedde opp denne prisen possession.According til kunden GHD MK4 styler regnes som en stor investering, vel verdt prisen. Og grunnene er ganske fantastisk og samlet de gjør det best. En global super merkevare GHD er et britisk selskap, og det er en Yorkshire selskap som tror på hardt arbeid i forkant av global hårpleie. [url=]billig ghd rettetang[/url] GHD hår styler bruker oppvarmede, keramiske plater til både rette og krølle håret. Riktig vedlikehold vil sikre din GHD styler varer like lenge som mulig. Rengjøring styling produktrester fra styler bør være en del av vanlig vedlikehold. Det vil holde styler fungerer på sitt beste. Du kan enkelt rengjøre GHD styler uten å forårsake noen damage.Ceramic hår straighteners foretrekkes både for salongen og hjem styling.

  • looker from clarisonic classic

    Posted by iouwanzi on 06/05/2013 10:40pm

    [url=]clarisonic classic[/url] Butland afsløret i en besked til en anden GB fodboldspiller, Karen Carney, at en Beats repræsentant besøgte holdet hotel på mandag, twitte: “. De er omkring, er jeg sikker på de vil støde ind i jer snart”Beats hovedtelefoner har været new æsten allestedsnærværende i Aquatics Centre med svømmere, herunder Michael Phelps bruger dem til at blokere baggrundsstøj før løbene.Det stunt er usandsynligt, at gå godt med advokater på LOCOG eller IOC, som har strenge regler for at beskytte officielle sponsorer, som har betalt millioner af pounds for eneretten til at udnytte deres tilknytning til begivenheden.Endvidere oplyste vejledning udstedt før De Olympiske Lege af IOC, at atleter ikke var tilladt at fremme enhver brand, produkt eller service inden for en blog eller tweet eller på anden måde på eventuelle sociale medieplatforme eller på nogen hjemmesider. [url=]clarisonic australia[/url] Dr. Dre Beats by Dre hovedtelefoner tendens til at være så dygtige i mange hovedtelefoner producerer. Blandt det store udvalg af Monster Beatshovedtelefoner med næsten alle håndsæt kan individuelt kunne være Fahion trend med blanding, med fremragende fordele. De behøver ikke nødvendigvis giver et individ af Dr. Dre hovedtelefoner som de to sider. [url=]clarisonic mia[/url] Fordelene og ulemperne ved de forskellige typer af hovedtelefonerHeadset hovedtelefoner, takket være en større enhed, lydkvaliteten er mere bedre, men på grund af nogle store volumen, ikke er nem at bære. Ørepropper lille enhed design, kompakt og let at bære, velegnet til udendørs brug. Ørekrog øretelefon typen headset med ørepropper i mellem et smukt udseende, komfortable at bære, lyde bedre egenskaber end ørepropper ulempe er følsom over for støj udefra, som er egnet til at bære i foråret, og denne sæson . Forskellige typer hovedtelefoner er anderledes, for at se om du ønsker at bruge under hvilke omstændigheder.

  • cheap authentic mlb jerseys,thailand l.a.galaxy jersey

    Posted by AffongeAtorge on 05/07/2013 11:20am

    The match up against Bettis, Barcelona include displaced only two golf ball. Barcelona displaced the golf ball, its because the power to make the purpose, as an alternative to the workforce support generally cannot resolve the issue. Barcelona support uneasiness easily into faults, to be able to Bettis, Barcelona once again immediately after shielding faults sustained the study, Bettis immediately after just simply 102 moments to be able to bust the Barcelona door, Pinto kicks will be lower, Alex Martinez header leading, [url=]Live soccer scores[/url] Pavon penetrates the forbidden community suitable rib eight yards place decreased tries for a takedown the far perspective. Even though Barcelona a few momemts after the equaliser, yet forty-third moments, Barcelona once again displaced the golf ball, after that Espinoza topple again, Ruben Perez 40 yards Division opportunity from the leading still left nearby. Shielding challenges on the team's online players have a very clear understanding, their particular passive observed the issue, look at the motivation, however the video game against Bettis, Barcelona support once again subjected to the interest deficit challenges, the workforce is not able to avoid rental the competition to be able to fico score. After the video game, Bettis is a collective thoughts series caught Barcelona, Barcelona disciplined along with goals, you'll find it constrains the 1st one half from the video game. In those days, Adriano Pavon become relatively baffling skin fail, one other will not likely waste products the opportunity, immediate against Pinto entrance. Inside Barcelona, additional stressing is a purpose which is their particular worth since it will be the problem. Even though team accomplished reversal, however the workforce support shadow in no way take away shilly-shally, Peake along with Adriano tried out to become exploited from the alternative blowout, yet these times Bettis failed to fico score a goal. Bettis discipline Pepe Mel fully by simply Messi, after the video game they sighed along with reported that will: "Messi, you actually are generally is unable connected with action. [url=]Fox soccer[/url] From the Saint moose Metz, they after action is just the competition because teaching cone. Nowadays, his first feel the golf ball about the purpose, in the face of a really problem, you actually think weak. Messi's presence, Barca without doubt much better, the truth is they inside virtually any workforce can help the workforce increase standards. Athletic Bilbao should also believe therefore. With regards to workforce heart, influence from the atmosphere from the stadium. Messi scored, everything turns into enjoyment. " Immediately after Sanchez in addition lauded Messi: "Messi on the review, for individuals will be a strong inspiration, needless to say you'll find an incentive to be able to your pet. "

  • lace babydoll lingerie

    Posted by Fishnetaj1079 on 03/29/2013 09:59am - Sexy Lingerie ShopBy signing up as an affiliate, you will be directing customers to purchase items in exchange for a commission On one of the calls he just casually mentioned that four months after installing the systems, he has not had a workmans compensation claim in two months, something that was very common before the cameras were installed - babydoll nightiesWarm colors are vibrant and exciting while cool colors have calming effect The baby doll lingerie style gets its name from; well - Fishnet BodystockingThey have lingerie from bustiers, corsets and babydolls The best thing is that all these dresses are available both online and offline at affordable prices for the customers - Maid LingerieSo, what is a wholesale lingerie? Let us know about it Hence, a blue bed sheet is also a unique gift - Lingerie TeddiesMermaids are a legendary mystical creatures of the deep seas, that posse the upper body of a female and lower body of a fish, and are known to be attention-grabbing and beautiful Included in its website are listings of hot offers, bestsellers, latest arrivals and on sale products

  • Sexy Babydoll Lingerie

    Posted by Fishnethy1021 on 03/29/2013 09:59am - Fishnet BodystockingsSchedule in home parties and order from wholesalers, distributors and dropshippers If the strap of the bra is coming up from under your rib cage the bra may be too small as well - cheap clubwear?Foxy Lady Boutiquejust in case - Nurse CostumesGot a nice set of abs? Look for an outfit that reveals your mid driftLingerie is  term that refer to fashionable undergarments that can be quite sensational - sexy lingerie teddiesTherefore, you should choose a wholesale lingerie dress as per your body type and size and the style that suits your personality A pajama set might not sound too sexy, but if it is silky, and buttons up the front, it can make your woman feel very sexy, especially if she is a plus size (size 18 or larger) - Cheap Bustiers?By wearing wholesale evening dresses and wholesale prom dresses, you can be the queen of an evening or prom night Invite your co-workers, family and friends to join you

  • Wholesale Sexy Dress

    Posted by Fishnetuy1065 on 03/29/2013 09:05am - Nurse CostumesThey have created all the latest in dreamgirl style including the most comprehensive ones One of the most popular types of lingerie is the baby doll lingerie set - black lace lingerieMermaids are a legendary mystical creatures of the deep seas, that posse the upper body of a female and lower body of a fish, and are known to be attention-grabbing and beautiful The smell of a jack-o-lantern burning, the sound of a doorbell ringing, the sight of an overflowing bowl of candy--all indicators that the fabulous children's holiday Halloween has arrived - Discounted LingerieEven if lingerie attracts you but is not of your size, you should avoid buying it Gradually creeping shorter, and featuring ever more daring fabrics, baby doll lingerie made the switch from simple nightwear to true sexy lingerie - sexy lingerie teddiesHow can the parties be made different? If you have a set way of throwing a party, why not consider having it someplace different — such as away from the office or at a different hotel or venue? Do you have just one holiday celebration or more? What about wearing costumes or holiday garb to work? Is your party just for employees or for their family members as well? How about going to a comedy club or hiring a comedy group? What about a Thanksgiving meal at work? How about creating a meal for the homeless or some other type of charitable meal that includes people other than just your employees and their families? The money you spend here will go miles toward boosting employee morale and, thus, your company's bottom line These wholesale dresses for women are designed in such a manner that whether they are wholesale prom dresses, wholesale prom gowns, wholesale evening gowns, whole cocktail dresses, wholesale party dresses or wholesale bridesmaid dresses, they can fit women of any shape and size - pink Sexy LingerieIf you offer a service, all of your income will be profit It’s so easy to get distracted from your aims and start surfing, or checking your email ten times a day instead of doing the stuff that matters

  • oakley sunglasses discount

    Posted by ugliliImpumpoxy on 03/29/2013 08:06am - fake oakley sunglasses cheap ray ban - ray ban sunglasses cheap cheap sunglasses online - sunglasses wholesale oakley discount - discount ray ban cheap sunglasses,,, - discount oakley sunglasses,,,,,o wholesale sunglasses

  • Fishnet Bodystockings

    Posted by Fishnetqe1056 on 03/29/2013 07:46am - babydoll nightgownsIf you are an eBay seller, you can sign up to be an eBay Trading Assistant or ask friends and family if they have anything they would like for you to try and sell for themLingerie category will be separated into few subcategories with more specific styles - womens babydollOne more interesting moment - on main picture maybe the model will be in black color but this company also offers this style in other color If all your bartenders are over pouring, that's a tremendous amount of money in a month - Body StockingsHowever there is a minute difference between baby doll lingeries and baby doll dresses The more skin you show, the hotter it is - cop costumeToday's modern corset is made from softer and suppler materials such as silk, satin and lace, (as well as leather) to name a few Buying wholesale products are the best way to increase your profit potential - Chinese ManufacturerDo they own a pet? Does his son have a big pile of books? Does he have a golf stick? Analyze and you can get a clue for a gift base on his hobby 2 is the busiest, most demanding time of our year

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Entire organizations suffer when their networks can't keep up and new opportunities are put on hold. Waiting on service providers isn't good business. In these examples, learn how to simplify network management so that your organization can better manage costs, adapt quickly to business demands, and seize market opportunities when they arise.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date