Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to determine the available stack space at run time?

I know that stack size is fixed. So we can not store large objects on stack and we shift to dynamic allocations (e.g. malloc). Also, stack gets used when there is nesting of function calls so we avoid recursive functions as well for this reason. Is there any way at runtime to determine how much stack memory is used so far and how much is left ?

Here, I am assuming linux environment (gcc compiler) with x86 architecture.

like image 257
Vinit Dhatrak Avatar asked Nov 07 '09 17:11

Vinit Dhatrak


3 Answers

There is a pthread API to determine where the stack lies:

#include <pthread.h>

void PrintStackInfo (void)
   {   pthread_attr_t Attributes;
       void *StackAddress;
       int StackSize;

   // Get the pthread attributes
   memset (&Attributes, 0, sizeof (Attributes));
   pthread_getattr_np (pthread_self(), &Attributes);

   // From the attributes, get the stack info
   pthread_attr_getstack (&Attributes, &StackAddress, &StackSize);

   // Done with the attributes
   pthread_attr_destroy (&Attributes);

   printf ("Stack top:     %p\n", StackAddress);
   printf ("Stack size:    %u bytes\n", StackSize);
   printf ("Stack bottom:  %p\n", StackAddress + StackSize);
   }

On i386, the stack starts at the bottom and grows towards the top.

So you know you have ($ESP - StackAddress) bytes available.

In my system, I have a wrapper around pthread_create(), so each thread starts in my private function. In that function, I find the stack as described above, then find the unused portion, then initialize that memory with a distinctive pattern (or "Patton", as my Somerville, MA-born father-in-law would say).

Then when I want to know how much of the stack has been used, I start at the top and search towards the bottom for the first value that doesn't match my pattern.

like image 120
Martin Del Vecchio Avatar answered Sep 19 '22 13:09

Martin Del Vecchio


Just read %esp, and remember its value goes down. You already know your defaulted max size from the environment, as well as your threads' starting point.

gcc has great assembly support, unlike some flakes out there.

like image 45
rama-jka toti Avatar answered Sep 22 '22 13:09

rama-jka toti


If your application needs to be sure it can use X MB of memory the usual approach is for the process to alloc it at startup time (and fail to start if it cannot alloc the minimum requirement).

This of course, means the application has to employ its own memory management logic.

like image 36
diciu Avatar answered Sep 22 '22 13:09

diciu