-
malloc() and free()
If I allocated a pointer using:
char *ptr = malloc(1024);
but messed around with the pointer address and such, say do this:
ptr = ptr + 20;
*ptr = *ptr + 100;
if I do free(ptr), will that work? I ask this because I did change the initial memory location that ptr was malloc(ed) with, and changed its values as well.
-
You must pass the same pointer value to free that was returned from malloc.
The example you posted will quite likely corrupt the heap.
Note that the line with 100 in it is fine, as it doesn't modify the pointer value.