C编程: Freeing nested multidimensional arrays inside structs

标签 c memory struct malloc free

编辑:由于 coderredoc 建议的表述不当,我将关闭这个问题。

我有一个自由函数的问题,我错误地将位置的地址作为参数。

    void freeMemory(Stack stp, int n){
    for(int i=0; i<n; i++){
        free(&(stp.signals[n].intervals));
    }
    free(stp.signals);

}

这是正确的代码(查看下面的更多信息)

    void freeMemory(Stack stp, int n){
    for(int i=0; i<n; i++){
        free(stp.signals[n].intervals);
    }
    free(stp.signals);

}

最佳答案

永远记住一件事,您将把使用 malloc 分配的任何内容传递给 free 及其 friend 。

这里传了free(&(stp.signals[i].intervals)); 为什么要传stp.signals[i].intervals的地址 它是 stp.signals[i].intervals,其中包含已分配 block 的地址。 (刚刚使用*alloc创建的内存块的起始地址)所以free(stp.signals[i].intervals) 是释放它的正确方法。

准确地说,你在这里所做的是未定义的行为。

来自标准7.22.3.3p2

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

关于C编程: Freeing nested multidimensional arrays inside structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778911/

相关文章:

GoLang - 填充结构数组

c++ - SWIG 如何使用 Lua 表从 Lua 中的 c 结构访问字节数组以进行操作

c - 取消引用指向结构的指针以访问其第一个成员

c - 如何将两个寄存器的 2 的补码值读入一个 int

c - pthread_mutex_timedlock 和死锁

linux - 如何测量应用程序或进程的实际内存使用情况?

linux - 从 U-boot shell 模式写入 NVRAM

c++ - 应用程序的返回码是一个 int16_t?

c - 进程未终止

c - 探索结构包装