Lapys
Lapys

Reputation: 946

Is it safe to always reallocate memory before freeing it - C++

Assume code like this:

#include <stdlib.h>

int main(int argc, char* argv[]) {
    int value = 42;
    void* pointer = (void*) &value;

    // Free stack memory
    free(pointer);

    return 0;
}

This code results in undefined behavior because it tries to de-allocate memory on the stack.


But I was wondering; What about re-allocating a pointer everytime before we free it.

#include <stdlib.h>

int main(int argc, char* argv[]) {
    int value = 42;
    void* pointer = (void*) &value;

    // Allocate pointer on heap, then free memory
    pointer = realloc(pointer, sizeof pointer);
    free(pointer);

    return 0;
}

My assumption being that this sends the pointer to heap memory so it can be freed appropriately.

All of this is with the context that the programmer does not know on what memory (heap or stack) the pointer is specified on (At which point, the design of the program comes into question, but I wouldn't digress).


Query

Is this a safe-way to ensure memory gets freed properly or is it improper and create garbage objects left in memory?

Upvotes: 0

Views: 210

Answers (1)

John3136
John3136

Reputation: 29266

You can't realloc stack memory - so you still have undefined behavior.

The realloc(3) man page will tell you this:

Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.

Upvotes: 13

Related Questions