Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting an array the wrong way [duplicate]

Possible Duplicate:
How could pairing new[] with delete possibly lead to memory leak only?

I was always told that it's not safe to call delete on an array allocated with new[]. You should always pair new with delete and new[] with delete[].

So I was surprised to discover that the following code compiles and runs ok, in both Debug and Release mode under VS2008.

class CBlah
{
public:
    CBlah() : m_i(0) {}

private:
    int m_i;
};

int _tmain(int argc, _TCHAR* argv[])
{
    for(;;)
    {
        CBlah * p = new CBlah[1000]; // with []
        delete p;                    // no []
    }
    return 0;
}

It took me a while to figure out why this works at all, and I think it's just luck and some undefined behaviour.

BUT... it made me wonder... why doesn't Visual Studio pick this up, at least in the Debug memory manager? Is it because there's lots of code out there that makes this mistake and they don't want to break it, or do they feel it's not the job of the Debug memory manager to catch this kind of mistake?

Any thoughts? Is this kind of misuse common?

like image 411
ben Avatar asked Nov 02 '10 13:11

ben


People also ask

How to avoid duplicate in JavaScript array?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

How do you remove Doubles from an array?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

How do you delete an array in Java?

We can use an ArrayList to perform this operation. To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.


2 Answers

It will certainly compile ok, because there is no information in the pointer (compile-time) which will see if pointer points to array or what. For example:

int* p;

cin>>x;
if(x == 0)
  p = new int;
else
  p = new int [10];

delete p; //correct or not? :)

Now , about running ok. This is called undefined behavior in C++, that is, there is no guarantee what will happen - everything can run OK, you can get a segfault, you can get just wrong behavior, or your computer may decide to call 911. UB <=> no guarantee

like image 131
Armen Tsirunyan Avatar answered Oct 03 '22 06:10

Armen Tsirunyan


It's undefined behavior and everything is fair in love, war and undefined behavior...:)

like image 41
Chubsdad Avatar answered Oct 03 '22 08:10

Chubsdad