0

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;
}
NotInCheck
  • 29
  • 4
  • 2
    It's not just telling you that there's a memory leak, it's telling you exactly why. "Common realloc mistake: 'str' nulled but not freed upon failure". If `realloc` fails, you overwrite `str` with `NULL`, losing the pointer previously held in `str`, which points to memory that is still allocated. You need to check the result of `realloc` before you overwrite the existing pointer. – Thomas Jager May 27 '22 at 19:22

0 Answers0