cmemory

How do I check the memory being used by my C code?


I am a new C programmer and the pointers + arrays are messing me over a lot. I don't get any errors and the code runs fine...until somewhere in the middle the code starts acting up because some element in an array is set to something other than I wanted it to be. I wanted to know if there is a program that visualizes the memory of the code after it has finished running?

E.g after I run:

#include <stdio.h>
int main(){
    int array[2] = {0,1};
    array[1] = 4;
    printf("%d\n",array[1]);
}

It will show a block of memory where array has two elements with 0 and 4 .

Right now to avoid running into a problem where the array contains elements from previous action I clear the memory of that array by doing:

memset(tokenized,0,MAX_CHARS);

It seems to work, but I don't know if its actually doing what I think it's doing at the back end.

Edit: I am using Valgrind now and I just want to know, how do I know what line the error is referring to? For example I got this:

==24394== Source and destination overlap in strncpy(0x7ff000006, 0x7ff000006, 6)
==24394==    at 0x4C2C236: strncpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==24394==    by 0x400D8A: tokenize_quotes (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394==    by 0x40184E: main (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394== 
==24394== Conditional jump or move depends on uninitialised value(s)
==24394==    at 0x4C2C007: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==24394==    by 0x400E06: tokenize_quotes (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394==    by 0x40184E: main (in /home/zee/Documents/seng265/repos/assignment2/a.out)
==24394== 

But I don't know what line the error is on? I know its something about strcpy Thanks!


Solution

  • Use Valgrind:

    Valgrind is a GPL'd system for debugging and profiling Linux programs. With Valgrind's tool suite you can automatically detect many memory management and threading bugs, avoiding hours of frustrating bug-hunting, making your programs more stable. You can also perform detailed profiling to help speed up your programs.​

    ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​