Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I call malloc() on a pointer twice (after freeing it)?

So, I know we shouldn’t try to access freed memory.
e.g.

int * x = calloc(10, sizeof(int));
free(x);
x[0] = 2; // results in data corruption

Most posts such as LINK say not to reuse pointers period. After calling free(), can I call malloc() (or calloc()) again on the same pointer? My understanding is that it will point to a new, unused section of memory now and be fine.
e.g.

int * x = calloc(10, sizeof(int));
free(x);

x = calloc(10, sizeof(int));
x[0] = 2;

what about if the previous memory location of the pointer is used by other variables now? e.g.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int * x = calloc(10, sizeof(int));
free(x);

... stuff happens here ...

x = calloc(10, sizeof(int));
x[0] = 2; 

>Solution :

The pointer only stores the value returned by malloc and this function does not know anything about this pointer.

You can assign pointer as many times as you need with the value returned by the malloc function if you free previously stored value, otherwise you will have a memory leak.

void foo(void)
{
    char *ptr;

    for(size_t i = 0; i < 10000000; i++)
    {
        ptr = malloc(rand() % 1000000);
        free(ptr);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading