[英]Realloc and uninitialized variables (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
函數之前完成了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);
}
天哪! 打開調試器解決了這個問題。 實際上,該代碼段存在一些問題。 我將函數初始化為在錯誤的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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.