我有一个需要返回字符串列表的程序。在编译时,字符串的数量,长度或字符串都是已知的。此外,在创建下一个字符串之前,每个字符串“增长”几次迭代:我使用realloc()和strcat()向每个字符串添加单词。有几个子例程可以将字符串添加到字符串数组或扩展字符串。
我的计划是这样过大,贴在这里,所以这里的一个小样本只是为了证明我是怎么做的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **result = NULL;
void function_1();
void function_2();
int main()
{
result = (char **)realloc (result,sizeof(char *) * 1);
result[0]= (char *)realloc(result[0],5 * sizeof(char));
strcat(result[0],"hello");
result[0]= (char *)realloc(result[0],10 * sizeof(char));
strcat(result[0]," world");
result = (char **)realloc (result, sizeof(char *) * 2);
function_1();
printf ("%s \n", result[0]);
printf ("%s \n", result[1]);
return 0;
}
void function_1(){
function_2();
result[1]= (char *)realloc(result[1],20 * sizeof(char));
strcat(result[1],"12345");
}
void function_2(){
result[1]= (char *)realloc(result[1],10 * sizeof(char));
strcat(result[1],"");
result[1]= (char *)realloc(result[1],15 * sizeof(char));
strcat(result[1],"asdfg");
}
所以基本上,我想创建一个新的字符串每次我用
result = (char **)realloc (result,sizeof(char *) * TOTAL_NUMBER_OF_STRINGS);
,每次我想扩展字符串我用
result[STRING_NUMBER]= (char *)realloc(result[0],sizeof(char) * (current_length_of_string + length_of_new_word));
代码的小部分我已经提供正常,但在我的节目时,我使用同样的办法,最终我得到的要么是这样的:
*** glibc detected *** ./uvicfmt3: realloc(): invalid next size: 0x081d1170 ***
或分段错误。
有人可能会提示我的方法有什么问题吗?我已经重写了我的程序中从头开始处理动态内存分配几次的部分,但问题仍然存在。
PS这是我的整个程序:http://pastebin.com/7WhehW18 format_file函数get的从外部调用。
不要在C.它确实投的malloc()'等'结果只是模糊的诊断。另外,''你好''需要**六个**字节。 –
你已经问过这个问题。 – karlphillip