When I run valgrind on this function, it says I’ve definitely lost 4 bytes. I know it’s because I’m redirecting the pointer x in x=y, thus losing access to the initial memory allocated in the first line. How do I fix this? What’s the correct principle here? I’m just learning C, so I’m trying to get the hang of all this. Thanks!
int main() {
int* x = malloc(sizeof(*x));
int* y = malloc(sizeof(*y));
*x = 2;
*y = 5;
x = y;
*y = 6;
*x = 4;
printf("y = %d\n", *y);
free(x);
free(y);
return 0;
}
xwas pointing to an int, then that address was overwritten byx = y;(as you expected) but the space that the previous address pointed to was not released.xandythen contain the same address and therefore both point to the same space in memory, thus yourfree()calls are both trying to free the same location.If you don’t want to leak those 4 bytes, put in
free(x);just beforex = y;