<p>I'm using MinGW with GCC 3.4.5 (mingw-special vista r3).</p>

<p>My C application uses a lot of stack so I was wondering is there any way I can tell programatically how much stack is remaining so I can cleanly handle the situation if I find that I'm about to run out.</p>

<p>If not what other ways would you work around the problem of potentially running out of stack space?</p>

<p>I've no idea what size of stack I'll start with so would need to identify that programatically also.</p>

[{'answer_id': 53834, 'author': 'Nathan Fellman', 'author_id': 1084, 'author_profile': 'https://Stackoverflow.com/users/1084', 'pm_score': 3, 'selected': False, 'text': "<p>Assuming you know the size of the full stack you could probably add some assembly code to read ESP.<br>\nIf you read ESP and save it aside in the main function you can compare the current ESP to the ESP you have in main and see how much ESP has changed.  That'll give you an indication of how much stack you're used.</p>\n"}, {'answer_id': 53836, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 4, 'selected': False, 'text': '<p>Taking the address of a local variable off the stack would work.  Then in a more nested call you can subtract the address of another local to find the difference between them</p>\n\n<pre><code>size_t top_of_stack;\n\nvoid Main()\n{\n  int x=0;\n  top_of_stack = (size_t) &amp;x;\n\n  do_something_very_recursive(....)\n}\n\nsize_t SizeOfStack()\n{\n  int x=0;\n  return top_of_stack - (size_t) &amp;x;\n} \n</code></pre>\n\n<p>If you code is multi-threaded then you need to deal with storing the top_of_stack variable on a per-thread basis.</p>\n'}, {'answer_id': 53900, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 3, 'selected': True, 'text': '<p>Raymond Chen (<a href="http://blogs.msdn.com/oldnewthing/default.aspx" rel="nofollow noreferrer">The Old New Thing</a>) has a good answer to this sort of question:</p>\n\n<blockquote>\n  <p>If you have to ask, you\'re probably doing something wrong.</p>\n</blockquote>\n\n<p>Here\'s some Win32 details on stack allocation: <a href="http://msdn.microsoft.com/en-us/library/ms686774.aspx" rel="nofollow noreferrer">MSDN</a>.</p>\n\n<p>If you think you might be limited by stack space, you will almost certainly be limited by available virtual memory, in which case, you will need to find a different solution.</p>\n\n<p>What exactly are you trying to do?</p>\n'}, {'answer_id': 53925, 'author': 'mweerden', 'author_id': 4285, 'author_profile': 'https://Stackoverflow.com/users/4285', 'pm_score': 3, 'selected': False, 'text': "<p>This is a problem I have given up on. With a lot of hacking and (mostly) praying, you can get a solution that works at a given time on a given machine. But in general there seems to be no decent way to do this.</p>\n\n<p>You will have to obtain the stack position and size from outside your program (on Linux you might get it from <code>/proc/&lt;pid&gt;/maps</code>). In your program you must somehow test where you are at the stack. Using local variables is possible, but there is no real guarantee that they are actually on the stack. You can also try to get the value from the stack pointer register with some assembly.</p>\n\n<p>So now you have the location of the stack, its size and the current position and you assume you know in which direction the stack grows. When are you going in stack-overflow mode? You better not do it close to the end because your estimation (i.e. address of local variable or value from stack pointer) is probably a bit too optimistic; it's not uncommon to address memory beyond the stack pointer. Also, you have no clue about how much room on the stack any given function (and the functions it calls) need. So you'll have to leave quite some room at the end.</p>\n\n<p>I can only advice you not do get into this mess and try to avoid very deep recursion. You might also want to increase your stack size; on Windows you have to compile this into the executable, I believe.</p>\n"}, {'answer_id': 54060, 'author': 'dmityugov', 'author_id': 3232, 'author_profile': 'https://Stackoverflow.com/users/3232', 'pm_score': 3, 'selected': False, 'text': '<p>check if your compiler supports stackavail()</p>\n'}, {'answer_id': 56596, 'author': 'botismarius', 'author_id': 4528, 'author_profile': 'https://Stackoverflow.com/users/4528', 'pm_score': 2, 'selected': False, 'text': "<p>maybe this will help for Windows platform only:</p>\n\n<p>in the PE header (IMAGE_NT_HEADERS) of your exe there are some records such as:</p>\n\n<pre>\n\ntypedef struct _IMAGE_NT_HEADERS {\n    DWORD Signature;\n    IMAGE_FILE_HEADER FileHeader;\n    IMAGE_OPTIONAL_HEADER32 OptionalHeader;\n} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;\n\ntypedef struct _IMAGE_OPTIONAL_HEADER {\n    ...\n    DWORD   SizeOfStackReserve;\n    DWORD   SizeOfStackCommit;\n    ...\n}\n</pre>\n\n<p>There is a simple way to obtain these values: using GetModuleHandle(NULL) will give you the imagebase (handle) of your module, address where you'll find a IMAGE_DOS_HEADER structure which will help you to find the IMAGE_NT_HEADERS structure (imagebase+IMAGE_DOS_HEADER.e_lfanew) -> IMAGE_NT_HEADERS, and there you'll find those fields: <b>SizeOfStackReserve</b> and <b>SizeOfStackCommit</b>.</p>\n\n<p>The maximum amount of space that the OS will allocate for your stack is SizeOfStackReserve.</p>\n\n<p>If you consider trying this, let me know and I will assist you. There is a way to obtain the size of stack used in a certain point.</p>\n"}, {'answer_id': 59579, 'author': 'Thomas Kammeyer', 'author_id': 4410, 'author_profile': 'https://Stackoverflow.com/users/4410', 'pm_score': 2, 'selected': False, 'text': "<p>On Linux, you would call getrusage and check the returned struct rusage's\nru_isrss member (integral unshared stack size).</p>\n\n<p>From the MINGW site and its sourceforge site's tracking of patches, I see that in May of 2008 there was some patching done around getrusage and it looks like it's been generally supported for quite a while. You should check carefully for any caveats in terms of how much of the typical Linux functionality is supported by MinGW.</p>\n"}, {'answer_id': 5864773, 'author': 'phoxis', 'author_id': 702361, 'author_profile': 'https://Stackoverflow.com/users/702361', 'pm_score': 5, 'selected': False, 'text': '<p>The getrusage function gets you the current usage . (see <a href="http://www.kernel.org/doc/man-pages/online/pages/man2/getrusage.2.html" rel="noreferrer"><code>man getrusage</code></a>).</p>\n\n<p>The <code>getrlimit</code> in Linux would help fetching the stack size with the <code>RLIMIT_STACK</code> parameter.</p>\n\n<pre><code>#include &lt;sys/resource.h&gt;\nint main (void)\n{\n  struct rlimit limit;\n\n  getrlimit (RLIMIT_STACK, &amp;limit);\n  printf ("\\nStack Limit = %ld and %ld max\\n", limit.rlim_cur, limit.rlim_max);\n}\n</code></pre>\n\n<p>Please give a look at <a href="http://man7.org/linux/man-pages/man2/setrlimit.2.html" rel="noreferrer"><code>man getrlimit</code></a>.\nThe same information could be fetched by <code>ulimit -s</code> or <code>ulimit -a</code> stack size row.\nAlso have a look at <code>setrlimit</code> function which would allow to set the limits.\nBut as the mentioned in the other answers if you need to adjust stack then probably you should re consider your design. If you want a big array why not take the memory from the heap ?</p>\n'}, {'answer_id': 8716410, 'author': 'Daniel James Bryars', 'author_id': 418246, 'author_profile': 'https://Stackoverflow.com/users/418246', 'pm_score': 2, 'selected': False, 'text': '<p>For windows: I\'ve done this before using the VirtualQuery function from Kernel32.dll. I only have an example in C# but it demonstrates the technique:</p>\n\n<pre><code>public static class StackManagement\n    {\n        [StructLayout(LayoutKind.Sequential)]\n        struct MEMORY_BASIC_INFORMATION\n        {\n            public UIntPtr BaseAddress;\n            public UIntPtr AllocationBase;\n            public uint AllocationProtect;\n            public UIntPtr RegionSize;\n            public uint State;\n            public uint Protect;\n            public uint Type;\n        };\n\n        private const long STACK_RESERVED_SPACE = 4096 * 16;\n\n        public unsafe static bool CheckForSufficientStack(UInt64 bytes)\n        {\n            MEMORY_BASIC_INFORMATION stackInfo = new MEMORY_BASIC_INFORMATION();\n            UIntPtr currentAddr = new UIntPtr(&amp;stackInfo);\n            VirtualQuery(currentAddr, ref stackInfo, sizeof(MEMORY_BASIC_INFORMATION));\n\n            UInt64 stackBytesLeft = currentAddr.ToUInt64() - stackInfo.AllocationBase.ToUInt64();\n\n            return stackBytesLeft &gt; (bytes + STACK_RESERVED_SPACE);\n        }\n\n        [DllImport("kernel32.dll")]\n        private static extern int VirtualQuery(UIntPtr lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);\n    }\n</code></pre>\n\n<p>BTW: This code can also be found on StackOverflow on another question which I asked when I was trying to fix a bug in the code: <a href="https://stackoverflow.com/questions/5303227/arithmetic-operation-resulted-in-an-overflow-in-unsafe-c-sharp">Arithmetic operation resulted in an overflow in unsafe C#</a><a href="https://stackoverflow.com/questions/5303227/arithmetic-operation-resulted-in-an-overflow-in-unsafe-c-sharp">enter link description here</a></p>\n'}]
['https://Stackoverflow.com/questions/53827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5330/']