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.
source
share