-2

I have a c++ code which recently started throwing segmentation fault. i know the issue is due to the uninitialized pointer. But my doubt is why this code started throwing seg fault suddenly. This code was not changed since 2010. Is it possible to have a segmentation fault without any change to the code? Here is the code:

void COB :: processfile()
{
ofstream *pbm_ptr; //uninitialiased ptr
..
while(currentRecord,readLine(_cobstream, FALSE))
{
...
if(_cobvalues[POS_REC_TYPE] == DETAIL)
{
    pbm_ptr = null; //initialising
...
}
else
{
  if(pbm_ptr != NULL)
    *pbm_ptr << currentRecord(0,RECORD_LENGTH) << endl; //segmentation fault
..
}

I would like to add one more point that after i get segmentation fault, if i rerun the same executable again with the same input file, there will not be any error for the second run. Can anyone tell me what is the cause of such result ?

user1768029
  • 415
  • 8
  • 22
  • 3
    Its likely caused by undefined behavior, and the funny thing about undefined behavior is anything can happen. You got lucky for a while and now it's blowing up in your face. – Borgleader Mar 03 '15 at 17:53
  • It's possible if your code was written badly, but just for whatever reason didn't cause a segmentation fault in the past. At any rate, I don't think you've provided near enough information for anyone to help resolve this issue. – Jonathan Wood Mar 03 '15 at 17:53
  • http://stackoverflow.com/help/how-to-ask In particular, we need an [SSCCE](http://www.sscce.org). – Baum mit Augen Mar 03 '15 at 17:53
  • Something that invokes Undefined Behavior cannot be considered as running fine. The fact that it was working and now it is not is implicitly what can happen with undefined behavior. – NathanOliver Mar 03 '15 at 17:58
  • I have added code snippet now. – user1768029 Mar 03 '15 at 18:17

1 Answers1

2

Of course yes, segmentation fault can happen even if it did not happened before.

First, you probably have a SEGV because of some undefined behavior, which is not reproducible in the general case. UB can be really naughty.

Then, the supporting C++ library might have changed, and the environment is probably different (so the stack at start of main is probably different)

At last, things like ASLR make pointer addresses non-reproducible.

If on Linux, you could disable ASLR, compile your code with all warnings and debug info (g++ -Wall -Wextra -g) and perhaps with -fsanitize=address, use valgrind and of course your gdb debugger (e.g. for post-mortem core(5) dump analysis).

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547