Basically the follow code read a stream until a determined char, if the string readed is bigger than initial_bytes (64 bytes), it doubles. The read function stops when it finds a EOF or the "char end" argument.
I scanned it with cppcheck and it showed me:
Id: memleakOnRealloc CWE: 401 Common realloc mistake: 'str' nulled but not freed upon failure
But I can't see how this is suposed to happen, I also runned it using valgrind and no memory leak was found. Is it a false positive?
string_t read_until(FILE *stream, char end) {
int bytes = INITIAL_BYTES;
string_t str = malloc(bytes * sizeof(char));
int char_counter = 0;
bool finished = false;
do {
if (char_counter == bytes) {
bytes *= 2;
str = realloc(str, bytes * sizeof(char));
}
char c = fgetc(stream);
if (end != EOF)
finished = (end_of_line(stream, c));
finished = finished || (c == end);
str[char_counter] = (finished ? '\0' : c);
char_counter++;
} while (!finished);
if (str[0] == '\0') {
free(str);
return NULL;
}
if (bytes > char_counter)
str = realloc(str, char_counter * sizeof(char));
return str;
}