未分配释放的指针(删除数组中的一个元素) [英] pointer being freed was not allocated(delete one element in an array)
问题描述
我是oop的初学者,这是我的问题
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;
}
和
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.
此外,新建"数组时,必须使用"delete []"将其释放.
Also, when you "new" an array, you must use "delete []" to release it.
thing* thingArray = new thing[64];
...
delete [] thingArray;
如果您尝试主动管理元素数组,则可能需要调查 std :: vector .
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.
这篇关于未分配释放的指针(删除数组中的一个元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!