gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:57:37 24 4
gpt4 key购买 nike

我试图从一个函数返回一个字符串数组,然后释放它使用的内存。代码如下:

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 debug0x100300060 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);

为了给终止零分配空间。

顺便说一句,sizeof (char) 始终为 1。

关于C: 正在释放的 malloc 错误指针未分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31385931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com