2017-06-07 32 views
-3

我分配在堆工会内存,我需要删除工会的对象时,工会的元素Id是900删除动态对象时出错?

请帮我删除groupUnion[i]对象的时候,Id低于900 是我的代码。

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() 

在此先感谢!

+1

你不能“unallocate”中的一个中间一块内存已经全部ocated记忆。不过,我很怀疑这是你想要的东西 - 如果你取消分配一块内存,你不能访问它,所以你可以不知道它是'标识== 900'。你真的想做什么? – yeputons

+0

[此链接说明](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)你如何能做到这一点。 –

+1

不要在C++中使用malloc/free。使用vector,unique_ptr,make_unique,new/delete。 –

回答

0

你的代码片段free groupUnion[i];groupUnion[i] = NULL让我假设你真正想表达的指针数组SettingUnion -objects而不是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() 
0

您可以分配的内存不是免费的一部分:免费groupUnion [我]

什么,但是你可以做的是分配单独的元素,然后逐个释放他们:

// 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()