C 编程:释放结构内的嵌套多维数组

C programming: Freeing nested multidimensional arrays inside structs

编辑:由于 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的东西传给它的朋友。

这里你已经传递了free(&(stp.signals[i].intervals));为什么你传递了stp.signals[i].intervals的地址它是stp.signals[i].intervals包含分配的块的地址。 (刚刚使用*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.