2011-11-30 45 views
1

可能重复:
Dynamically grown array of strings动态成长字符串数组和子程序

我有一个需要返回字符串列表的程序。在编译时,字符串的数量,长度或字符串都是已知的。此外,在创建下一个字符串之前,每个字符串“增长”几次迭代:我使用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的从外部调用。

+0

不要在C.它确实投的malloc()'等'结果只是模糊的诊断。另外,''你好''需要**六个**字节。 –

+1

你已经问过这个问题。 – karlphillip

回答

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"); 
  1. 你可以不知道的是,第一个结果[0]为NULL,因为你永远不将其设置为NULL;
  2. 结果相同的问题[0]字符串可能包含垃圾,因为未初始化;
  3. 在第一次重新分配你分配5个字符,然后你写了6个字符('\ 0'为字符串终止);
  4. 第二次realloc你总共分配了10个字符,而“hello world \ 0”是12个字符(不考虑你可能因为前面的strcat已经有些问题)。

虽然前两个点可能不是问题(您可能会意外地发现它们已经归零),但点3,4是一个问题。

关于第1点和第2点: 当您使用malloc或realloc进行分配时,内存不会被初始化,并且它可能包含任何内容。 这意味着如果您希望在那里找到0,则需要将memset设置为0(如果您执行重新分配,则应该注意仅将新分配的字节置0)。

当你分配一个指针数组时,你可能想把它们全部设置为0(第一次)。对于一个字符串,它是足够的,你的第一个字符设置为0 这意味着你应该做的是这样的:

result = (char **)realloc (result,sizeof(char *) * 1); 
    memset(result, 0, sizeof(char *) * 1); 
    result[0]= (char *)realloc(result[0],6 * sizeof(char)); 
    result[0][0] = '\0'; 
    strcat(result[0],"hello"); 

    result[0]= (char *)realloc(result[0],12 * sizeof(char)); 
    strcat(result[0]," world"); 
+0

非常感谢您的帮助。你能解释一下第二点你的意思吗?我不完全确定你在那里指的是什么。 – user1073407

+0

我编辑回答你的评论。 – Teudimundo