我试图从函数返回字符串数组,然后释放它使用的内存。代码如下:
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地址= 0x1003000000x100300030 0x100300040 0x100300050 0x100300060 0x100300070地址= 0x1003000000x100400030 0x100300030 0x100300040 0x100300050 0x100300060地址= 0x100400000testC(562,0x7fff73e71310) malloc: ***错误的对象0x3000000000000;未分配被释放的指针***在malloc_error_break中设置一个断点进行调试0x100300060 0x100300070 0x100300030 0x100300040 0x100300050 0x3000000000000程序以退出码:9结束您需要将此添加到dataTest
函数的return dataReturn;
之前:
dataReturn[i] = NULL ;
否则您的while (data[i]) {}
将继续超出所需的范围。
而不是:
dataReturn[i] = malloc( sizeof(char) * (strlen(*str)) );
写:
dataReturn[i] = malloc(strlen(*str) + 1);
,以便为结束零分配空间。
BTW sizeof (char)
总是1.