Realloc和未初始化的变量(valgrind)

时间:2014-08-01 20:51:03

标签: c memory-management malloc heap valgrind

对于我的生活,我无法弄清楚为什么Valgrind会报告以下警告:

==4988== Use of uninitialised value of size 8
==4988==    at 0x4E62C3F: set_library (mainroutines.c:67)
==4988==    by 0x400E81: main (in /media/src/bin/driver)
==4988==  Uninitialised value was created by a heap allocation
==4988==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4988==    by 0x4E6301F: create_input_data (supportroutines.c:43)
==4988==    by 0x400DAA: main (in /media/src/bin/driver)
==4988== 
==4988== Use of uninitialised value of size 8
==4988==    at 0x4E62C61: set_library (mainroutines.c:68)
==4988==    by 0x400E81: main (in /media/src/bin/driver)
==4988==  Uninitialised value was created by a heap allocation
==4988==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4988==    by 0x4E6301F: create_input_data (supportroutines.c:43)
==4988==    by 0x400DAA: main (in /media/src/bin/driver)
==4988== 

同时,set_library功能如下所示:

void set_library (Foo* in_data, const int nrows, char* in_string) {
    const int str_length = strlen(in_string);
    char** new_string_array = NULL;

    if (in_data->stored_string==NULL) {
      in_data->stored_string = malloc(sizeof(char*)*1);
    } else {
      new_string_array = realloc(in_data->stored_string, sizeof(char*)*(nrows+1));
      in_data->stored_string = new_string_array;
    };  

    in_data->stored_string[nrows] = malloc(sizeof(char)*str_length);    // first uninitialized warning
    strcpy(in_data->stored_string[nrows], in_string);                   // second uninitialized warning
};

in_data->stored_string的声明是char**。我还检查了stored_string = NULL在调用set_library函数之前完成了realloc。如果没有调用if,我似乎没有收到错误。任何人都有想法导致问题的原因吗?

修改---------------------

D'哦!打开调试器解决了这个问题。实际上,有问题的片段有一些问题。我放置了函数来初始化错误的void set_library (Foo* in_data, const int nrows, char* in_string) { const int str_length = strlen(in_string)+1; char** temp_string_array = NULL; temp_string_array = realloc(in_data->stored_string, sizeof(*in_data->stored_string)*(nrows+1)); in_data->stored_string = temp_string_array; in_data->stored_string[nrows] = malloc(sizeof(char)*str_length); strcpy(in_data->stored_string[nrows], in_string); } 括号内的值。无论如何,评论中提出了有效点,所以......

{{1}}

1 个答案:

答案 0 :(得分:0)

d'哦!打开调试器解决了这个问题。实际上,有问题的片段有一些问题。我放置了函数来初始化错误的if括号内的值。无论如何,评论中提出了有效点,所以......

void set_library (Foo* in_data, const int nrows, char* in_string) {
    const int str_length = strlen(in_string)+1;
    char** temp_string_array = NULL;

    temp_string_array = realloc(in_data->stored_string, sizeof(*in_data->stored_string)*(nrows+1));
    in_data->stored_string = temp_string_array;
    in_data->stored_string[nrows] = malloc(sizeof(char)*str_length);    
    strcpy(in_data->stored_string[nrows], in_string);  
}