Well, there are always limits. You could perhaps check with getrlimit to get the stack size, but then again what's the point? The function alloca does the same thing, it could return NULL, but it doesn't.
You could use malloc, but it has limits as well. Passing a too big value to malloc can be worse than a simple crash. (I'm thinking a lot of swapping - not sure if it's better than a simple crash.)
Nevertheless it can be made safe:
Code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void die(int sig)
{
fprintf(stderr,"Number too big!\n");
exit(1);
}
void scaryfunc(void)
{
unsigned long size;
printf("How many megabytes to allocate?\n");
scanf("%lu",&size);
size *= 1024*1024;
char s[size];
strcpy(s,"Big buffer");
printf("%s\n",s);
}
int main(void)
{
stack_t ss;
ss.ss_sp = malloc(SIGSTKSZ);
ss.ss_size = SIGSTKSZ;
ss.ss_flags = 0;
sigaltstack(&ss, NULL);
struct sigaction act;
memset (&act, '\0', sizeof(act));
act.sa_handler = die;
act.sa_flags = SA_ONSTACK;
sigaction(SIGSEGV,&act,NULL);
scaryfunc();
return 0;
}