delete operator

Aug 30, 2014 at 2:41pm
what is the difference b/w the 2 delete statements in the following code:

1
2
3
4
   double* pp =new double[5];
    
/*statement 1*/     delete[] pp;
/*statement 2*/     delete  pp; // working .. but does it produce the same result as above? 


Edit: How can i check what is doing what .
IDE - Xcode 5.1;
statement 1 and statement 2 make up separate programs


Thanks !
Last edited on Aug 30, 2014 at 3:43pm
Aug 30, 2014 at 3:09pm
http://en.cppreference.com/w/cpp/language/delete

"working" is misleading. It is an error.
Aug 30, 2014 at 3:11pm
It didn't show any error in my IDE !?
Aug 30, 2014 at 3:45pm
Your IDE has no way to know that pp points to an array and not to an individual 'double'. It's not your IDE's job to show you logic errors.

So this will not show as an error. Instead, it'll surface as a memory leak (ie: your program is allocating memory, then never releasing it).


If you are using array new[], then you must use array delete[].
If you are using individual new, then you must use individual delete.


Although... in modern C++ ... if you are ever manually deleting, you are probably doing something very wrong. In this case, you don't even need new/delete at all:

 
double pp[5];  // <- just put it on the stack.  No need for new/delete 


Or... if the size of the array is not known at runtime, you can use a vector:

 
std::vector<double> pp(5);  // <- use a vector, no need to delete anything 



Even when you do need to dynamically allocate... you should put it in a smart pointer so it will be automatically deleted. Never give memory the opportunity to leak.
Aug 30, 2014 at 5:25pm
@Disch This is the kind of answer I wanted : It surfaces as a memory leak. Can i view this leak ?

I was just learning how the c++ worked prior to c++11 where stuff like smart pointer were not there….
Aug 30, 2014 at 5:29pm
@Disch This is the kind of answer I wanted : It surfaces as a memory leak. Can i view this leak ?


Some tools (Valgrind comes to mind) will track memory allocation and point out if/where you have leaks. Other than that, they can be difficult to see. Especially if they're small.
Aug 30, 2014 at 6:12pm
> prior to c++11 where stuff like smart pointer were not there….

Smart pointers have always been an inseparable part of mainstream C++ programming.

The most widely used variants of smart pointers became a part of the standard library in 2011. These cater to the most common use cases; home-grown smart pointers, tailored to meet specific needs, are still needed and are still used.
Topic archived. No new replies allowed.