我试图从函数返回一个字符串数组,然后释放它使用的内存。代码如下:
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
答案 0 :(得分:8)
您需要在return dataReturn;
函数中dataTest
之前添加此内容:
dataReturn[i] = NULL ;
否则您的while (data[i]) {}
将继续超出预期。
而不是:
dataReturn[i] = malloc( sizeof(char) * (strlen(*str)) );
写:
dataReturn[i] = malloc(strlen(*str) + 1);
为终止零分配空间。
BTW sizeof (char)
始终为1。