'valgrind' is a command in cs50 IDE that checks if there's any memory leaks in your program. It will find out errors like:
1. If you touched memory block that you are not supposed to touch. Usually you'll get a 'segmentation fault' for it, but sometimes you might get lucky and 'malloc()' allocated a few more blocks than you coded so you don't get a segmentation fault. But 'valgrind' will be able to find faults like that.
2. If you forget to free up memory that you no longer use.
To use 'valgrind', you need to finish compiling your program first, and then just add 'valgrind' in front of './program_name':
valgrind ./memory
After you run it, lots of error messages might come up and hard to understand. You can add "help50" before that to help interprete it more and make it easy to understand:
help50 valgrind ./memory
For example, here's a simpe program called 'memory.c':
#include <stdlib.h>
void f(void)
{
int *x = malloc(10 * sizeof(int));
x[10] = 0;
}
int main(void)
{
f();
return 0;
}
So we can see that there are 2 memory problems in this code:
x[10]: we got out of bound of the allocated block.
And we didn't free memory blocks after use.
We can run after compiling:
valgrind ./memory
Lots of error messages might come up. If we don't understand, just add 'help50' before it:
help50 valgrind ./memory
Then it will be much easier to understand, and we can correct the errors.