C++ 删除动态对象时出错?
我正在为堆中的union分配内存,当union的元素Id为900时,我需要删除union的对象 Id为900时,请帮助我删除groupUnion[i]对象 下面是我的代码C++ 删除动态对象时出错?,c++,file,malloc,free,C++,File,Malloc,Free,我正在为堆中的union分配内存,当union的元素Id为900时,我需要删除union的对象 Id为900时,请帮助我删除groupUnion[i]对象 下面是我的代码 groupUnion = (SettingsUnion *) malloc(sizeof(SettingsUnion) * (NumAttrs + 1)); if(groupUnion == (SettingsUnion *) NULL) { return (FALSE); } for (unsigned int i
groupUnion = (SettingsUnion *) malloc(sizeof(SettingsUnion) * (NumAttrs + 1));
if(groupUnion == (SettingsUnion *) NULL)
{
return (FALSE);
}
for (unsigned int i=0; i < NumAttrs; i++)
{
inFile.read(reinterpret_cast<char*>(&groupUnion[i]),sizeof(SettingsUnion));
if(groupUnion[i].Id == 900)
{
free groupUnion[i]; // this is bad how can i delete groupUnion[i] when groupUnion[i].Id == 900
groupUnion[i] = NULL;
}
}
inFile.close()
提前谢谢 您的代码片段自由groupUnion[i];groupUnion[i]=NULL允许我假设您实际上想要表示指向SettingUnion对象的指针数组,而不是SettingUnion对象数组。
所以你的代码看起来就像我使用了你的MalC/Cype风格,但是在C++中你实际上会使用NeX/DELL:
无法释放部分已分配内存:free groupUnion[i] 但是,您可以单独分配元素,然后单独释放它们:
// not sure why you need the +1 (anyway you allocate an array of pointers to the struct here. Consider using new operator)
groupUnion = (SettingsUnion **) malloc(sizeof(SettingsUnion *) * (NumAttrs + 1));
if(groupUnion == (SettingsUnion *) NULL)
{
return (FALSE);
}
for (unsigned int i=0; i < NumAttrs; i++)
{
// you allocate the individual groupUnion here:
groupUnion[i] = (SettingsUnion *) malloc(sizeof(SettingsUnion));
if(groupUnion[i] == (SettingsUnion *) NULL)
{
return (FALSE);
}
inFile.read(reinterpret_cast<char*>(&groupUnion[i]),sizeof(SettingsUnion));
if(groupUnion[i].Id == 900)
{
free groupUnion[i]; // this is bad how can i delete groupUnion[i] when groupUnion[i].Id == 900
groupUnion[i] = NULL;
}
}
inFile.close()
不能在已分配内存的中间分配一段内存。然而,我非常怀疑这是你想要的——如果你释放一段内存,你就不能再访问它了,所以你就不能知道它的Id==900。你真正想做什么?如何做到这一点。不要在C++中使用MalC/C。使用向量、唯一\u ptr、使\u唯一、新建/删除。
// not sure why you need the +1 (anyway you allocate an array of pointers to the struct here. Consider using new operator)
groupUnion = (SettingsUnion **) malloc(sizeof(SettingsUnion *) * (NumAttrs + 1));
if(groupUnion == (SettingsUnion *) NULL)
{
return (FALSE);
}
for (unsigned int i=0; i < NumAttrs; i++)
{
// you allocate the individual groupUnion here:
groupUnion[i] = (SettingsUnion *) malloc(sizeof(SettingsUnion));
if(groupUnion[i] == (SettingsUnion *) NULL)
{
return (FALSE);
}
inFile.read(reinterpret_cast<char*>(&groupUnion[i]),sizeof(SettingsUnion));
if(groupUnion[i].Id == 900)
{
free groupUnion[i]; // this is bad how can i delete groupUnion[i] when groupUnion[i].Id == 900
groupUnion[i] = NULL;
}
}
inFile.close()