0

I have a long C code which gets segmentation fault because a pointer variable x is pointed to NULL somewhere in the code (there are many writes to this variable and I did not write the code myself), and later an attempt has been made to read it's value resulting in a segmentation fault.

Now I can get the line where the variable x was accessed which resulted the segfault using gdb, but I'm interested to know when it (x) was assigned to the value NULL. There are many writes to this variable in the code and checking this manually soon becomes tedious. Is there an automated way to find when some variable x is assigned to a specific value? Maybe using gdb or some value analysis tool?

Shafiul
  • 2,832
  • 9
  • 37
  • 55
  • 6
    Set a watchpoint? Something like `watch x`? – EOF Nov 30 '15 at 19:23
  • Building off of @EOF's comment: see http://stackoverflow.com/questions/3099537/how-to-monitor-variables-in-gdb-and-log-it-if-it-meets-certain-conditions?rq=1 – tonysdg Nov 30 '15 at 19:24
  • It might not be assigned a specific value of `NULL` by a code statement. It could be because that's the default initialisation of a global variable, or in a block of memory obtained by `calloc()`, or the *partial* explicit initialisation of a `struct` or `array` which would fill the rest with `0` . – Weather Vane Nov 30 '15 at 19:25
  • ..or a buffer index overrun, or an overwrite via some other pointer, maybe in another thread in another module in an unrelated subsystem. Not trying to be depressing, or anything.. – Martin James Nov 30 '15 at 19:56
  • Thanks everyone for the informative comments. If I understand the comments correctly, value of a pointer variable `x` may become `null` in any of the ways mentioned above. Or, it might get corrupted in many ways and may later point to an illegal memory address, accessing which may cause `segfault`. Is there a way to check all of these possibilities with `gdb`? – Shafiul Dec 01 '15 at 18:01

0 Answers0