Amin
Amin

Reputation: 261

Delete a pointer c++

I have a c++ program that in a part of it the size of pointer is increased if user enters more elements. This pointer has a type associated with structure Entry and the function that increases the pointer size is

Entry *size_increase(Entry *neuu, int *size){
   *size = *size+10;
   Entry *new_neu = new Entry[*size];
   for (int i=0; i<*size; ++i) {
       new_neu[i]=neuu[i];
   }

   return new_neu;
}

The pointer neuu is the pointer to be increased and the size is its initial size. At the end of this function I would like to delete the input pointer, neuu, to free the memory.

Problem is: if I have this sequence

delete neuu;
return new_neu;

instead of the one that I have in the code above, the compiler stops after taking two user inputs and prints the error

error for object 0x1002042b8: pointer being freed was not allocated

How can I delete the pointer then?

Edit: Some users are asking about how initially neuu is allocated. Initially I have

Entry *neu = new Entry[1];

and whenever the user tries to input the second item a function is called as

   neu = size_increase(neu,size);

Both of these two happen inside the main function.

Upvotes: 1

Views: 173

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36463

As your neuu has been created with new[] you should use delete[] instead of delete.

Upvotes: 3

Related Questions