Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the limits of the stack in C / C++?

Tags:

My question is pretty simple and straightforward: if I have e.g. 1MB of RAM assigned to the program's stack, can I get the addresses of the start and the end, or the start and the length?

I'm using Visual Studio 2013.

like image 796
rev Avatar asked Feb 24 '15 23:02

rev


People also ask

Is there limit of stack?

Yes, stack is always limited. In several languages/compilers you can set the requested size. Save this answer.

How large is the stack in C?

Stacks are temporary memory address spaces used to hold arguments and automatic variables over subprogram invocations. The default size of the main stack is about eight megabytes.

How do you calculate stack size?

Count the number of complete strings, multiply by 8 (since "STACK---" is 8 bytes long), and you have the number of bytes of remaining stack space.


2 Answers

You should question your assumptions about stack layout.

Maybe the stack doesn't have just one top and bottom

Maybe it has no fixed bottom at all

Clearly there's no portable way to query concepts which are not portable.

From Visual C++, though, you can use the Win32 API, depending on Windows version.

On Windows 8 it is very easy, just call GetCurrentThreadStackLimits

Earlier versions need to use VirtualQueryEx and process the results somewhat. Getting one address in the stack is easy, just use & on a local variable. Then you need to find the limits of the reserved region that includes that address. Joe Duffy has written a blog post showing the details of finding the bottom address of the stack

like image 109
Ben Voigt Avatar answered Sep 19 '22 18:09

Ben Voigt


GetCurrentThreadStackLimits seems to do what you're looking for, getting the lower/upper boundaries of the stack into pointer addresses:

ULONG_PTR lowLimit; ULONG_PTR highLimit; GetCurrentThreadStackLimits(&lowLimit, &highLimit); 

Looks like it is only available on Windows 8 and Server 2012 though.

Check the MSDN

like image 38
E. Moffat Avatar answered Sep 18 '22 18:09

E. Moffat