0

I want to calculate the stack size for a given callgraph function.

for ex:lets say i have a function which calls the other function , that function again invoke other function like so on.

For the above ex, how to calculate the stack size using GCC or MINGW or google framework.

I need the stack size for each function or thread wise.

Please help me in this. Thanks in advance.

Pavel
  • 7,436
  • 2
  • 29
  • 42
  • 3
    possible duplicate of [How to determine maximum stack usage?](http://stackoverflow.com/questions/389219/how-to-determine-maximum-stack-usage) – Pavel Jun 29 '14 at 14:00
  • There is no standard(portable) way to find out the stack size of a function. However we should be aware about the maximum stack size which a particular OS gives to particular thread. Typically it ranges from 1MB to 4MB. Our program should not exceed beyond the maximum size.Typically it could happen due to recursive function call in C program especially if do not have proper termination of these recursion. – Mantosh Kumar Jun 29 '14 at 14:06
  • Just as stack size is settable in most development environments, it would have to be a utility function/macro provided by that environment, if any, that would keep track of stack usage at any one point in time. – ryyker Jun 29 '14 at 14:34

1 Answers1

1

Like other comments noted, there is no standard way to determine the stack size of a program. You can, however, calculate the stack size a specific program needs on a given platform with a little hack.

For this, you can keep track of the lowest stack address a local variable in any function had. You then subtract this from the address of the last local variable in the main() function, and you have the maximum stack size (give or take, say: 100 bytes for temporary stack variables needed for expression evaluation).

The following program illustrates this:

#include <stdio.h>

void * lowestStackAddress = ( void * ) 0xFFFFFFFF;

int myFunc( int n )
{
  int m;

  /**** remember lowest stack address ****/
  if ( &m < lowestStackAddress )
    lowestStackAddress = &m;

  /**** do some arbitrary recursive algorithm the compiler can't optimize away ****/
  if ( n == 1 )
    return 1;

  if ( n % 2 == 1 )
    m = n * 3 + 1;
  else
    m = n / 2;

  return myFunc( m );
}

int main ( int argc, char * argv[] )
{
  int n;
  void * mainStackAddress = ( void * ) &mainStackAddress;

  printf( "mainStackAddress=%p\n", mainStackAddress );

  n = myFunc( 5 );

  printf( "Largest stack size: %d\n", 
    ( char * ) mainStackAddress - ( char * ) lowestStackAddress );

  getchar();

  return 0;
}

You need to place that check/assignment for lowestStackAddress in every function that doesn't call another function itself.

Pretty ugly hack, and I don't know if this is even applicable because you might not be able to compile all the necessary source code yourself, but it was just a thing that came to my mind.

KlaFier
  • 159
  • 2