c-Realloc和未初始化的变量(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**。我还检查了一下,以确保在调用set_library函数之前完成了stored_string = NULL。当没有调用realloc时,我似乎没有得到错误。有人知道是什么导致了这个问题吗?

编辑------------------

哦!打开调试器解决了这个问题。事实上,有问题的片段有一些问题。我将初始化值的函数放在错误的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);  
}

D'oh!打开调试器解决了这个问题。事实上,有问题的片段有一些问题。我将初始化值的函数放在错误的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);  
}

最新更新