This web page was written by Tia Newhall but has been slightly edited for the CS33 class.
In the class directory for today is a program called memory.c with bad memory access errors. You can use valgrin on this program to find the errors.
Links to on-line valgrind help pages
% valgrind ./memory % valgrind ./memory >& out # re-direct valgrind (and memory) output to file 'out'
If you look through the out file, you may see memory errors listed like this (each line of valgrind output starts with ==processid==):
==7444== Invalid write of size 1 ==7444== at 0x804841D: main (memory.c:11) ==7444== Address 0x41b302d is 0 bytes after a block of size 5 alloc'd ==7444== at 0x4022AB8: malloc (vg_replace_malloc.c:207) ==7444== by 0x80483F0: main (memory.c:6)This tells me that in function main, at line 11 in memory.c, my program is writing 1 byte beyond the array that was allocated at line 6 in function main (7744 was the process ID of my running program). If I look at lines 11 and 6 of my program, the error is obvious (after my loop executes, I put a '\0' in position 5 of the array which is beyond the end of array s, on the last iteration):
5 int i; 6 char *s = malloc(5 * sizeof(char)); 7 8 for (i = 0; i < 5; i++) { 9 s[i] = 65+i; 10 } 11 s[i] = '\0';