0

everyone. Recently, I have been learning how to develop a function to delete a pointer safely. However, something weird happened when I made my safe_delete() code shown below.

#include <iostream>
using namespace std;

template <class T>
void safe_delete(T* ptr) {
  delete ptr;
  ptr = NULL;
}

int main() {
  int var = 10;
  int* ptr = &var;
  safe_delete<int>(ptr);
}

Running the code in repl.lt (I am afraid that it might cause a memory leak), here is what I get:

munmap_chunk(): invalid pointer
exited, aborted

What does the above error mean? I currently guessed that munmap_chunk() is some function used in the implementation of delete.

The above source code is taken from stack overflow's answers. Something is weird. I just added templates to the function, which I believe is correct.

Can anyone tell me why is this error happening?

Cliff Chiang
  • 15
  • 2
  • 7
  • "*I just added templates to the function, which I believe is correct.*" Can you clarify why you think this is the case? It would be nice if you added the link to the SO answer you're using. – cigien Oct 27 '20 at 03:29
  • First, this code is no different from simply `delete ptr;`. It assigns `NULL` to the function's argument, and that argument goes away at the end of the function. I suppose it could be written as `safe_delete(T*&ptr)`, which would modify the pointer that it was called with. But that is only "safe" if you **also** check whether a pointer is null before using it. Pointer safety comes from sound design, not from coding hacks. – Pete Becker Oct 27 '20 at 13:24

0 Answers0