I know people keep telling me to read the documentation, and I haven't got the hang of that yet. I don't specifically know what to look for inside the docs. If you have a tip on how to get used to reading the docs, give me your tips as a bonus, but for now here is my question. Say in a simple program if we allocate
some chunk of memory I can free
it once I am done, right? here is one such a program that does nothing, but allocates
and deallocates
memory in the heap.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s = malloc(10);
free(s);
return (0);
}
After we compile this, if we run valgrind
we can see that everything is freed. Now, here is just a little bit of a twist to the previous program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *s = malloc(10);
s++;
free(s);
return (0);
}
Here, before I free it, I increment the address by one, and all hell breaks loose. Free doesn't seem to now that this chunk of memory was allocated (even though it is a subset of allocated memory). In case you want to see it, here is my error message.
*** Error in `./a.out': free(): invalid pointer: 0x0000000001e00011 ***
Aborted (core dumped).
So this got me thinking.
- Does c keep track of memory's allocated on the heap
- If not, how does it know what to free and what to not?
- And if it has such a knowledge, why doesn't c automatically
deallocate
such memories just before exiting. why memory leaks?