DigviJay Patil
DigviJay Patil

Reputation: 1006

Delete Operator behavior when called on array in C++?

I have following line of code.

Code Sample 1

char * arr = new char[10];
arr++;
delete arr;

Code Sample 2

char * arr = new char[10];
delete arr;

I have two sample codes. Code sample one is crashing at delete while code sample 2 works okay. There is an only difference of arr++. What exactly happens in these two code samples. Can anybody explain?

Upvotes: 0

Views: 72

Answers (3)

Thomas Jager
Thomas Jager

Reputation: 5265

C++ does not support deleting elements in an array, as a C array is a reserved contiguous memory block. You may be looking for C++ vectors.

With them, you can do something like: (Modified example code from the link)

#include <iostream>
#include <vector>

int main()
{
    // Create a vector containing integers
    std::vector<int> v = {7, 5, 16, 8, 6, 3, 5, 6};

    // Add two more integers to vector
    v.push_back(25);
    v.push_back(13);

    // Iterate and print values of vector
    for(int n : v) {
        std::cout << n << '\n';
    }

    v.erase(3);
    v.erase(5, 6);

    for(int n : v) {
        std::cout << n << '\n';
    }
}

A reference specificially about Visual C++ can be found at https://msdn.microsoft.com/en-us/library/9xd04bzs.aspx#vector__erase.

Upvotes: 1

wally
wally

Reputation: 11002

It is not possible to delete a single element because delete must be used to delete the same memory that was allocated.

It is crashing because the pointer that new returns must be the same one that is used for the call to delete.

Incrementing the pointer and using that means that the program no longer sees the other bookkeeping information (possibly stored just before the pointer that new returned)

Also, you should use delete[] to delete an array. For this reason, the following is undefined behavior:

char * arr = new char[10];
delete arr;

It should be:

char * arr = new char[10];
delete[] arr;

Upvotes: 7

rams time
rams time

Reputation: 339

proper way to delete the array of allocations,

char * arr = new char[10]; delete[] arr;

// when you do this one element won't be deleted and will cause leak

char * arr = new char[10];
arr++ 
delete[] arr;

Upvotes: 0

Related Questions