c - 在尝试释放()之前确定结构成员是否具有有效数据

标签 c memory-management malloc free

我正在使用下面的代码释放 meshes 结构中的 malloced 内存,该结构包含 triangleArraysfaces

这会崩溃,因为并非 struct 中的每个位置都有数据。如果 struct 包含数组成员中的数据,我只想调用 free。但是使用 if (self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces !=NULL) 似乎不起作用。

for (int meshIdx = 0; meshIdx <=meshTriangleArrays; meshIdx ++) {
    for (int triangleArrayIdx = 0; triangleArrayIdx <=1; triangleArrayIdx ++) {
        if (self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces !=NULL) {
            free(self.meshes[meshIdx].triangleArrays[triangleArrayIdx].faces);
        }
    }
}

最佳答案

在空指针上调用 free 实际上没问题。

您没有提供足够的代码来完全诊断此问题,但需要注意以下几点:

  • 您需要确保 self.meshes[...].triangleArrays[...].faces 始终被初始化,或者通过调用 malloc (或诸如此类),或将其设置为 NULL。否则,它可能(很可能会)是一个随机垃圾指针,您无权free
  • 您需要确保所有不同的self.meshes[...].triangleArrays[...].faces 指针都是不同 指针。您只能在 malloc 指针上调用一次 free。例如,像这样:
    int * p = (int *) malloc(sizeof(int));
    free(p);
    free(p); // undefined behavior
    
    可能导致崩溃。

关于c - 在尝试释放()之前确定结构成员是否具有有效数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8525680/

相关文章:

c 返回变量并释放 malloc 内存

c - 如何仅包含 header 中的定义

function - Get-ChildItem -Recurse 抛出 System.OutOfMemoryException

c++ - malloc 在 Linux 中挂起

objective-c - C和Objective-C中返回地址的内存分配

c - 安全结构嵌入式系统

c - 使用 malloc 时出错

iphone - 为 iOS 和 XCode 4.3 交叉编译开源 c 库

C realpath 函数不适用于源文件中定义的字符串

c++ - 包含#include 指令的宏定义