You are not logged in.

#1 2005-07-18 22:24:31

phrakture
Arch Overlord
From: behind you
Registered: 2003-10-29
Posts: 7,879
Website

catching segfaults (C++)

Ok... this is a rough one... admittedly, once a segfault occurs, the program is in an undefined state and should be exited immediatly... however, it might be nice to report *where* this actually occured.

class segfault_handler
{
   std::string msg;
public:
   segfault_handler(int line, char* file)
   {
      //create message beforehand, as this will
      //  not work AFTER the segfault
      std::stringstream ss("segfault caught: ");
      ss << file << " @ " << line << std::endl;
      msg = ss.str();

      signal(SIGSEGV,&segfault_handler::handle);
   }

   static void handle(int sig)
   {
      std::cout << msg;
      abort();
   }   
};

#define SEGFAULT_CHECK() segfault_handler _seg_handler__(__LINE__,__FILE__)

int main()
{
   SEGFAULT_CHECK();
   int i = 22/0;
}

happy segfaulting!

Offline

Board footer

Powered by FluxBB