[Solved] Can’t reallocate memory after deleting a static/dynamic pointer


From your post:

Delete Deallocates storage previously allocated by a matching operator new.

When you use:

float x, y; x = y = 0;
float * p = &x;
delete p;

you are not following that statement.

p does not point to an object that was allocated by operator new. It points to a local variable on the stack.

With your updated code, you did allocate memory by calling new but you changed p so that it points to a variable on the stack.

float *p = new float(3.4);  // p points to object returned by new
float x, y; x = y = 0;
p = &x;                     // p points to x. The previous memory is leaked

Consequently,

  1. Your program has a memory leak.
  2. Your program is still subject to undefined behavior when it executes delete p;.

What’s the solution to fixing the following code.

Solution 1 Don’t use p after the line delete p; as though it is a valid pointer since it is not.

Solution 2 Allocate new memory, assign it to p and use p only after that.

int main(){
  float *p = new float(3.4);
  delete p; // I need to delete p right at this part of code.

  p = new float; // Allocate new memory
  *p = 2.1;
  std::cout << *p;
  delete p;      // Deallocate the memory before program ends
}

9

solved Can’t reallocate memory after deleting a static/dynamic pointer