Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a pointer to a vector

I have a const std::vector<double> *vecPtr inside a class. I want to correctly deallocate memory, so what should my destructor look like?

I tried ~ClassA() { delete[] vecPtr; } , but i get an error

*** Error in `./test': free(): invalid pointer: 0x00007fff8c643a98 ***
Aborted (core dumped)

Does delete[] work only if vector is filled with pointers?

EDIT:

I use vecPtr like this: vecPtr = &vec;

If i use just delete i get *** Error in ./test': double free or corruption (fasttop): 0x00000000008fcb20 ***

like image 962
jabk Avatar asked Dec 11 '22 02:12

jabk


1 Answers

It depends on how you created vecPtr. If you used vecPtr = new std::vector<double>, you should use delete vecPtr;

If vecPtr is created by array new, such as vecPtr = new std::vector<double>[3];, you should use array delete, delete[] vecPtr;

EDIT

If you used vecPtr = &vec;, and if vec is an auto variable, which used automatic memory, or vec is a static variable or global variable, which used static memory, you should not delete it, it will be deallocated automatically. Only dynamic memory could be deleted.

like image 115
songyuanyao Avatar answered Dec 27 '22 13:12

songyuanyao