Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer being freed was not allocated(delete one element in an array)

I am a beginner of oop, here is my question

int main(){
        int *p = new int[3];
        p[0] = 1;
        p[1] = 2;
        p[2] = 3;
        int* q = p;
        p++;  //here!
        delete p;
}

and

int main(){
        int *p = new int[3];
        p[0] = 1;
        p[1] = 2;
        p[2] = 3;
        int* q = p + 1;
        p++;  //here!
        delete p;
}

got bugs: pointer being freed was not allocated but and

int main(){
        int *p = new int[3];
        p[0] = 1;
        p[1] = 2;
        p[2] = 3;
        int* q = p + 1;
        delete p;
}

seems fine! I want to delete one element in this array. Can someone tell me the reason for the bug?

like image 411
ivory Avatar asked Feb 14 '23 21:02

ivory


1 Answers

Memory is allocated in contiguous blocks, and must be returned in the same way. It is best to assume that your memory block comes with a small prefix that the allocator uses to determine where it came from and how large it was.

Also, when you "new" an array, you must use "delete []" to release it.

thing* thingArray = new thing[64];

...

delete [] thingArray;

If you are trying to actively manage the array of elements, you may want to investigate a std::vector instead.

#include <vector>

std::vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
// v.size() is now 3 (num elements)
v.erase(v.begin()); // remove the first integer.
// v now "looks" like { 20, 30 }
// v.size() is now 2, not 3.
like image 94
kfsone Avatar answered Apr 28 '23 19:04

kfsone