Today, I saw Baidu know someone asked me how to detect stack overflow. I started with curiosity and checked it. I found that there is a powerful library libsigsegv on linux, it can detect Stack Overflow (maybe implemented by signal ). I tested it. That's OK. This library can be downloaded at http://www.gnu.org/software/libsigsegv.
#include <stdio.h> #include <stdlib.h>#include "sigsegv.h"static int size = 0;void oink() { int garbage[1024]; // push this onto the stack. //#ifdef DEBUGsize += sizeof(int); fprintf(stderr, "allocated %d kb of stack memory\n", size); //#endif /* DEBUG */ oink(); } voidstackoverflow_handler (int emergency, stackoverflow_context_t scp){ printf ("Stack overflow caught."); exit(0); //sigprocmask (SIG_SETMASK, &mainsigset, NULL); //sigsegv_leave_handler (stackoverflow_handler_continuation, // (void *) (long) (emergency ? -1 : pass), NULL, NULL);}#ifndef SIGSTKSZ# define SIGSTKSZ 16384#endifint main() { char mystack[SIGSTKSZ];stackoverflow_install_handler (&stackoverflow_handler, mystack, sizeof (mystack)); oink(); return 0;}