Reputation: 253
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?
Upvotes: 4
Views: 3703
Reputation: 24249
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.
Upvotes: 9
Reputation: 2620
delete
is used for deallocation of dynamically allocated memory (by new
). delete
is not used for deleting elements.
The bug is the following: firstly you allocated memory so after int *p = new int[3];
in p
pointer is memory address of the allocated space. Then you add 1 to this address in the p++
line, which means that p
is pointing now to different place in memory. Then your delete
fails because you try to deallocate memory at the modified address.
Upvotes: 0