How to calculate remaining stack in Linux when using C

I am working on a program that typically uses a lot of stack memory. Is there any way to find out the remaining space on the stack? It is on a Linux platform.

Thank!!

+3
source share
2 answers

Is there a way to find out the remaining space on the stack

Yes, there is: for the main thread, you can simply write &argcto main in some global one (for example, int *g_addr_argc), then call getrlimit(RLIMIT_STACK, ...)and compare the address of some local ones with it, for example

char a_local;
struct rlimit rlim_stack;

if (getrlimit(RLIMIT_STACK, &rlim_stack) == 0 &&
    rlim_stack.rlim_cur != RLIM_INFINITY &&
    (uintptr_t)g_addr_argc - (uintptr_t)&a_local > rlim_stack.rlim_cur - 8192) {
  fprintf(stderr, "Danger: getting too close to the stack limit\n");
}

This will only work for the main thread. If your application is multithreaded, you can use pthread_getattr_npto find information about your current stack stack.

+6
source

setrlimit. , ( ) .

#include <sys/resource.h>

int main (int argc, char **argv)
{
    const rlim_t kStackSize = 16 * 1024 * 1024;   // min stack size = 16 MB
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0)
    {
        if (rl.rlim_cur < kStackSize)
        {
            rl.rlim_cur = kStackSize;
            result = setrlimit(RLIMIT_STACK, &rl);
            if (result != 0)
            {
                fprintf(stderr, "setrlimit returned result = %d\n", result);
            }
        }
    }

    // ...

    return 0;
}
+2

All Articles