简体   繁体   中英

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.

由于你的neuu是用new[]创建的,你应该使用delete[]而不是delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM