cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : catch segmentation fault
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programm...
Articles
Lounge
Jobs

-

post  catch segmentation fault

rajeevr642 (3)
Is there any way to catch segmentation fault
for example ............

#include<iostream>
using namespace std;
int main()
{
try{

char *p;
strcpy(p,"How r u");
}
catch(const exception& er)
{
cout<<Got Segmentation Fault<<endl;
}

}

It is a segmentation fault program.How can i print the sentence inside catch.I also tried catch(bad_alloc).
Plzz help me
|
Bazzy (539)
In order to have catch getting any exception, use ... as argument:
1
2
3
4
5
6
7
8
try
{
   //your code
}
catch(...)
{
   //any error goes here
}
|
exception (321)
You can't catch segfaults. Segfaults lead to undefined behavior - period (err, actually segfaults are the result of operations also leading to undefined behavior. Anyways, if you got a segfault, you also got undefined behavior invoked, so it doesn't really matter...). And the OS takes control from your program ASAP, which actually is a Good Thing.
|
rajeevr642 (3)
thanks for ur reply.I read that in tutorials.but some where saying that, it
is generating signals, SIGSEGV signals.Is there any way to catch this
???
|
jsmith (958)
man 2 signal

or

man 2 sigaction

[EDIT: above assumes Un*x]

However, be aware of two things:
1) your signal handler can't do much more than set a flag indicating that your process needs to handle the signal;
2) SIGSEGV means something happened in your program that you as the programmer were not expecting to happen. At that point, you don't really know what state your program is in, if it is even possible to continue execution. For example, you might have seg faulted because you corrupted the heap previously. If the heap is corrupt, then not only can you not malloc/free or new/delete anything (which implies you cannot use any STL containers at all, including std::string), but you can't even do things like printf() or cout since they _could_ attempt to allocate memory behind the scenes. In other words, while you can catch SIGSEGV, there isn't much more you can do than just abort. (Not even exit() works, because exit() will run destructors which could attempt to free memory).



| Last edited on
rajeevr642 (3)
hi
thanks for ur reply
i will try to catch this
|

Registered users can reply in this forum.
Home page | Privacy policy
© cplusplus.com, 2000-2009 - All rights reserved - v2.2
Spotted an error? contact us