take care while using new and deleteThis tip submitted by rajender on 2011-11-19 04:54:04. It has been viewed 4185 times.
Rating of 4.2 with 5 votes
Let take a simple use of new and delete operators.
new allocates memory and returns pointer to that memory to use while in case of delete we have to provide a pointer to a memory to deallocate but delete does not know that it is going to delete the memory which was created by new, it is programmer responsibility to use the created memory and then delete it. Moreover, you must never use delete on a pointer that you did not allocate because someone else may still be using the memory.
Here's an example of how you can easily mis-use delete:
int* p =new int; int x; p=&x; delete p;
The above code looks simple but it has a memory leak and will crash with a segmentation fault when you try to delete a pointer, & x, that you did not allocate.
Help your fellow programmers! Add a tip!