C – 释放数组内的指针

我一直试图让我所有的指针,我使用malloc初始化为一个指针数组(或指针指针,也许),这样我就可以通过该数组并释放每个指针与类似的东西自由(ptr_array [I]);而不必单独释放每一个.

我相信这是可能的,但是我的代码有些麻烦,因为应该释放所有东西的功能(我宁愿将它全部保存在一个单独的函数中,如果可能的话)显然无法正确编辑“子指针“,似乎它们被复制而不像”主指针“.

这是代码,让我难过:

#include <stdlib.h>
#include <stdio.h>

void free_test(int** arg){
    printf("\tReceived arg addr: %p\n",arg);
    printf("\tFreeing arg[0] = %p\n",arg[0]);
    //And, just to MAKE SURE that arg[0] is ver, we do this:
    printf("\tIn-function ver[0] = %d\n",arg[0][0]);
    arg[0][0] = 2;
    printf("\tIn-function ver[0] = %d\n",arg[0][0]);

    free(arg[0]); //This one doesn't work...
    free(arg); //This one works though.
}

int main(){
    int** var;
    int* ver;
    int i;
    printf("ver addr 1: %p\n", ver);
    ver = malloc( sizeof(int) * 3 );
    printf("ver addr 2: %p\n", ver);
    for(i=0;i<3;i++){
        ver[i] = 5*i;
    }
    for(i=0;i<3;i++){
        printf("ver[%d]: %d\t(@ %p)\n",i,ver[i],&(ver[i]));
    }
    printf("var addr 1: %p\n", var);
    var = malloc( sizeof(int *) );
    printf("var addr 2: %p\n", var);
    var[0] = ver;
    printf("var[0] addr = %p\n", var[0]);
    free_test(var);
    printf("ver[0] new value: %d\n", ver[0]);
    //free(var); (free(arg) works in the function, so this one throws an error.)
    printf("So far so good, now break.\n");
    free(ver);
    printf("Didn't break. :(\n");
    return 0;
}

这是它目前给我的输出:

ver addr 1: 0x8048679
ver addr 2: 0x8b0f008
ver[0]: 0   (@ 0x8b0f008)
ver[1]: 5   (@ 0x8b0f00c)
ver[2]: 10  (@ 0x8b0f010)
var addr 1: 0xad7ff4
var addr 2: 0x8b0f018
var[0] addr = 0x8b0f008
    Received arg addr: 0x8b0f018
    Freeing arg[0] = 0x8b0f008
    In-function ver[0] = 0
    In-function ver[0] = 2
ver[0] new value: 0
So far so good, now break.
Didn't break. :(

我对C不太好,所以任何帮助都会受到赞赏.特别是因为ver [0]的值在函数内部被改变,但不在外部,我猜这将与为什么free(…)也不起作用有关.

提前致谢.

最佳答案 我对C的了解正在逐渐消失,但IIRC后续的内存释放会导致未定义的行为.因此,您无法保证能够发现任何错误.如果我理解正确,行为将根据特定的操作系统,编译器和stdlib实现(甚至特定的程序运行)而变化很大.

附:我的VS2012 VC编译器在free(ver);中断了.输出是:

ver addr 1: CCCCCCCC
ver addr 2: 00B8AFF0
ver[0]: 0       (@ 00B8AFF0)
ver[1]: 5       (@ 00B8AFF4)
ver[2]: 10      (@ 00B8AFF8)
var addr 1: CCCCCCCC
var addr 2: 00B85BF0
var[0] addr = 00B8AFF0
        Received arg addr: 00B85BF0
        Freeing arg[0] = 00B8AFF0
        In-function ver[0] = 0
        In-function ver[0] = 2
ver[0] new value: -17891602
So far so good, now break.
点赞