I get this Valgrind output (that’s the only error I get):
==20627== Conditional jump or move depends on uninitialised value(s)
==20627== at 0x804913A: main (main.c:223)
My main.c roughly looks like this:
//other code
char **sets;
//other code
//char** get_char_sets(FILE *source);
sets = get_char_sets(config_file); // I malloc the sets in here
//other code
int i = 0;
while(sets[i]){ // line 223
free(sets[i]);
i++;
}
free(sets);
//other code
get_char_sets looks like this:
char** get_char_sets(FILE *source){
char **sets = malloc((n + 1) * sizeof(char*));
for(int i=0;i<=n;i++){
sets[i] = malloc(1 * sizeof(char));
}
//rest of function
return sets;
}
I understand that valgrind says that i’m working with an uninitialized variable, the only one I can possibly see is sets, but it gets malloc()ed in get_char_sets() and than assigned with the returned pointer.
How can I get rid of that valgrind error in order to correct my code?
There is no limit on the value of
i, which will eventually result in out of bounds:Change to (something like):
You could also add a
NULLsentinel value intosetsand thewhileas is would be fine.