On Linux you get a segmentation fault if your code tries to write past the stack.
The size of the stack is a properties inherited between processes. If you can read or modify in the the shell using commands like ulimit -s
(in sh
, ksh
, zsh
) or limit stacksize
(tcsh
, zsh
).
From a program the size of the stack can be read using
#include <sys/resource.h>
#include <stdio.h>
struct rlimit l;
getrlimit(RLIMIT_STACK, &l);
printf("stack_size = %d\n", l.rlim_cur);
I don't know of a standard way to get the size of the available stack.
The stack starts with argc
followed by the contents of argv
and a copy of the environment, and then your variable. However because the kernel can randomize the location of the start of the stack, and there can be some dummy values above argc
, it would be wrong to assume that you have l.rlim_cur
bytes available below &argc
.
One way to retrieve the exact location of the stack is to look at the file /proc/1234/maps
(where 1234
is the process ID of your program). Once you know these bounds you can compute how much of your stack is used by looking at the address of the latest local variable.