Search code examples
cmemory-leakssegmentation-faultgdbvalgrind

Opposite of a Heisenbug, segmentation fault that appear ONLY when debugging, but program works fine


I've a written a simple C program with two data structures implemented as ADT, so I dynamically allocate the memory for them

Everything was working fine, until I've decided to add a int value inside a struct, nothing dynamically allocated, classic plain old simple static memory allocation, but since I've added it I've started having a segfault in a pretty safe function that shouldn't segfault at all.

I've thought about a memory allocation error, so I've tried to not free and reuse a pointer variable I was using, but instead use another variable, and doing so the program went fine. Pissed off by all the times I had to deal with this kind of errors, I've re-enabled that free I was talking before, recompiled and made a run with valgrind.

To my surprise, there was absolutely no memory leak, no segmentation fault, not any kind of interruption, just a warn about Conditional jump or move depends on uninitialised value(s), but that's a wanted behavior (if (pointer == NULL) { }) so I've run the executable directly from command line and again, everything went fine, so the situation it's this:

Program without the new int value in the struct:

  • Compile : check
  • Runs : check
  • Valgrind analisys: No memory leakage, just the warn
  • Debug (gdb) : check

Program with the new int value in the struct:

  • Compile : check
  • Runs : check
  • Valgrind analisys: No memory leakage, just the warn
  • Debug (gdb) : Segfault

So I think that's the opposite of a Heisenbug, a bug that shows itself only and absolutely only when debugging, how can I try to fix this?


Solution

  • OK thanks to @weather-vane and @some-programmer-dude I've noticed that effectively I wasn't initializing the variable valgrind was complaining about, and I've misunderstood the valgrind warn, I was reading it as You should not use a if to check if variables are NULL