I have the following C code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
while (1) {
int *test = malloc(sizeof(*test));
test = 500;
free(test);
}
return 0;
}
The free function does not seem to work as the allocated memory grows to 2GB within a few seconds. What is the problem?
You can only free a pointer that is a return of malloc.
In writing test = 500, you've changed the memory location pointed to by test. Trying to free that is undefined behaviour.
To assign a value to your allocated integer, derefence it: *test = 500;
test = 500;
This changed the memory address. Therefor the original memory you allocated was never freed.
Maybe you meant to write:
*test = 500;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With