21E. Finding and Fixing Causes of Memory Faults

Memory faults are a serious error. If your program gets a memory fault, use a debugger to track down exactly where the fault occurs. When the memory fault occurs and the program stops, look at the values of pointers, arrays and array indices at that point. If you are not sure whether a pointer p is valid, ask the debugger to show the value of *p using debugger command

  print *p

Pointers are shown in hexadecimal notation (base 16). In a Linux system, a null pointer is shown as either 0x0 or (null); a pointer into the heap is a relatively small number such as 0x6a003c; and a pointer into the run-time stack is a very large number, such as 0xfffffffffffa2004.

If something happens that appears to be impossible, then you should suspect that your program has used a dangling pointer. Sometimes it is easy to localize the error. But keep in mind that the actual error might have been made well before the memory fault occurs, and might be well removed from the place in your code where it occurs. In that case, you are on your own. The best approach is tracing.