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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With