what is the difference between deleting a pointer, setting it to null, and freeing it.
delete ptr;
vs.
ptr=NULL;
vs.
free(ptr);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your question suggests that you come from a language that has garbage collection. C++ does not have garbage collection.
If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an “orphaned” block of memory that remains allocated but is now unreachable — a leak. Leaks only cause a program to crash if they build up to a point where no memory is left to allocate.
There’s also the converse situation, where you
deletea block of memory using a pointer, and later try to access that memory as though it was still allocated. This is possible because callingdeleteon a pointer does not set the pointer to NULL — it still points to the address of memory that previously was allocated. A pointer to memory that is no longer allocated is called a dangling pointer and accessing it will usually cause strange program behaviour and crashes, since its contents are probably not what you expect — that piece of memory may have since been reallocated for some other purpose.[EDIT] As stinky472 mentions, another difference between
deleteandfree()is that only the former calls the object’s destructor. (Remember that you must calldeleteon an object allocated withnew, andfree()for memory allocated withmalloc()— they can’t be mixed.) In C++, it’s always best to use static allocation if possible, but if not, then prefernewtomalloc().