C: 正在释放的 malloc 错误指针未分配

C: malloc error-pointer being freed was not allocated

我正在尝试从一个函数中 return 一个字符串数组,然后释放它使用的内存。代码如下:

int main(int argc, const char * argv[])
{
    for (int m = 0; m < 10000; m++) {
        char **data = dataTest();

        int i = 0;
        while(data[i]) {
            printf("%p ",data[i]);
            free(data[i]);
            i++;
        }
        printf(" address= %p.\n",data);
        free(data);
    }

    return 0;
}

函数如下:

char **dataTest()
{
    char *row[] = {"this", "is", "a", "data", "string", NULL};
    char **str = row;
    char **dataReturn = (char **) malloc(sizeof(char *) * 6);

    int i = 0;
    while (*str) {
        dataReturn[i] = malloc(sizeof(char) * strlen(*str));
        strcpy(dataReturn[i++], *str);
        str++;
    }

    return dataReturn;
}

一开始运行的很好,但是很快就报错了。下面是结果。地址以某种方式出错并且发生 malloc 错误。有人遇到过同样的问题吗?

0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100400030 0x100300030 0x100300040 0x100300050 0x100300060  address= 0x100400000.
testC(562,0x7fff73e71310) malloc: *** error for object 0x3000000000000:     
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
0x100300060 0x100300070 0x100300030 0x100300040 0x100300050 0x3000000000000                 
Program ended with exit code: 9

您需要将此添加到 dataTest 函数中的 return dataReturn; 之前:

dataReturn[i] = NULL ;

否则你的 while (data[i]) {} 将继续比预期的更远。

而不是:

dataReturn[i] = malloc( sizeof(char) * (strlen(*str)) );

写入:

dataReturn[i] = malloc(strlen(*str) + 1);

以便为终止零分配space。

顺便说一句 sizeof (char) 总是 1。