0

I have an exercise about pointer in c++. Below is my code.

int* temp = NULL;
delete (temp);

Is it worthy to delete (temp) like above? Does it mean that event I point variable (temp) to NULL, but since I declare temp as int*; which the keyword store on the heap. Do I still need to delete temp explicitly?

Thong Ton
  • 11
  • 1
  • `delete NULL` and `delete nullptr` are safe. – selbie Mar 28 '20 at 07:34
  • 1
    Does this answer your question? [Is it safe to delete a NULL pointer?](https://stackoverflow.com/questions/4190703/is-it-safe-to-delete-a-null-pointer) – Andy Mar 28 '20 at 07:34
  • Deleting a null pointer is perfectly valid. – PaulMcKenzie Mar 28 '20 at 07:34
  • 1
    There is no harm, nor point, in firing `operator delete` on a null pointer. The standard specifically accounts for this as equivalent to a no-op. That said, from your post I'm not convinced you know what a pointer even *is*, or how they behave/are-used, so some review in your reference material [or a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is probably in order. – WhozCraig Mar 28 '20 at 07:35
  • 1
    `NULL` represents a value, a pointer cannot *point* to it. A pointer can only have a *null pointer value*, which `= NULL` achieves. `int*` does not indicate storage on the heap. Whether some object is has dynamic storage duration ("heap") is a matter of whether you use `new` to create it. You only need to `delete` what created with `new`. I second the suggestions in the comment above mine. – walnut Mar 28 '20 at 07:39
  • Sometimes code in a destructor is `if (foo_ptr != nullptr) delete foo_ptr;` but that code is redundant and more verbose than it should be, which is `delete foo_ptr;`. In modern C++, shouldn't need to do that because it could be declared `std::unique_ptr foo_ptr;` and then it manages itself. – Eljay Mar 28 '20 at 12:44

0 Answers0