I'm working on a fairly involved c program that is using a linked list of structures. There is a global variable declared at the top of one of my .c files (queue_head). This variable is now getting overwritten mysteriously, which causes seg faults.
Is there some way to find out the layout of my variables in memory. My best guess as to the cause is that something is writing past the end of it's memory and overwriting the queue_head memory location.
To test that I reversed the positions of queue_head and queue_tail in my source file, and the next time I ran the program, queue_tail was getting corrupted but queue_head was fine.
Of course it could be an errant pointer, but my belief is that it's something behind it in memory getting written to past it's memory allocation.
Is there a way to see how c maps out the variables short of disassembly?
Variables are generally laid out in order of appearance in file, but if program has several files, then it's harder to predict. You can print their addresses to find possible offender:
printf("%p %p\n", &queue_head, &fishy_var);
But what's good in finding previous variable? It might well happen that broken code doesn't reference it directly.
A better approach is to use debugger. For example if you can run program in gdb, then you can use watchpoint to break at location where memory gets corrupted: watch queue_head
. After this program will break every time value of queue_head changes, including legitimate uses. To isolate legitimate uses add dummy pointer variable just before queue_head and watch it:
void *fishy_var;
queue *queue_head;
And then in gdb:
break main
run
watch fishy_var
continue
This should lead right to the offending code.
Note, that you'd better put printf I showed earlier at the start of main, to 1. make sure variables are consecutive in memory and 2. make sure compiler doesn't optimize away unused fishy_var.