RagHaven
RagHaven

Reputation: 4327

How to figure out remaining stack in Linux while using C

I am working on a program that tends to use a lot of stack memory. Is there a way I can find out the remaining space on the stack ? This is on the linux platform.

Thanks!!

Upvotes: 3

Views: 901

Answers (2)

Employed Russian
Employed Russian

Reputation: 213385

Is there a way I can find out the remaining space on the stack

Yes, there is: for the main thread, you can simply record &argc in main in some global (e.g. int *g_addr_argc), then call getrlimit(RLIMIT_STACK, ...) and compare address of some local to it, e.g.

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 would only work for the main thread. If your application is multi-threaded, you can use pthread_getattr_np to find information about your current thread stack.

Upvotes: 6

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29519

You can set the stack size yourself in your code, using setrlimit. Then you don't have to wonder, and you can increase it (within reason) as you see fit.

#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;
}

Upvotes: 2

Related Questions