我正在为堆分配一个内存的内存,当联合的元素Id
为900时,我需要删除联合对象。
当Id
为900时,请帮助我删除groupUnion[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()
预先感谢!
您的代码片段 free groupUnion[i];groupUnion[i] = NULL
让我假设您实际上想向SettingUnion
-Objects 表示 pointer的数组,而不是SettingUnion
-Objects的数组。因此,您的代码看起来如下(我使用了您的malloc
/free
-风格,尽管在C 中,您实际上会使用new
/delete
(:
groupUnion = (SettingsUnion **) malloc(sizeof(SettingsUnion*) * (NumAttrs + 1));
if(groupUnion == NULL)
{
return (FALSE);
}
for (unsigned int i=0; i < NumAttrs; i++)
{
groupUnion[i] = malloc(sizeof(SettingsUnion));
inFile.read(reinterpret_cast<char*>(&groupUnion[i]),sizeof(SettingsUnion));
if(groupUnion[i]->Id == 900)
{
free groupUnion[i];
groupUnion[i] = NULL;
}
}
inFile.close()
您无法释放分配的内存的一部分: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()