Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free function not working

Tags:

c

memory-leaks

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?

like image 226
MichaelAttard Avatar asked Feb 06 '26 01:02

MichaelAttard


2 Answers

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;

like image 141
Bathsheba Avatar answered Feb 07 '26 20:02

Bathsheba


test = 500;

This changed the memory address. Therefor the original memory you allocated was never freed.

Maybe you meant to write:

*test = 500;
like image 38
nvoigt Avatar answered Feb 07 '26 20:02

nvoigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!