Skip to content

Failure of realloc clobbers and leaks memory. #3

@smcameron

Description

@smcameron

In src/main.c:

342   while ((line_len = getline(&buf, &buf_size, file_to_read)) != -1) {
343     if ((i * sizeof(char*)) >= size) {
344       result.values = realloc(result.values, size * 1.5);
345       size *= 1.5;
346     }

If realloc fails, then result.values will get clobbered and leak the original memory. There are several other instances of the pattern "x = realloc(x, size);" which will clobber/leak. Should be something like this:

    char *tmp = realloc(x, size);
    if (tmp) {
        x = tmp;
    } else {
        /* probably nothing good will happen if realloc is failing. */
       free(x);
       x = NULL;
       fprintf(stderr, "Out of memory.\n"); /* or whatever */
       return -1; /* or something ... */
   }
       

Also, realloc(x, size * 1.5) will allocate the same amount of space if size happens to be 1 because the implicit cast back to int will truncate it. Maybe that case can't happen, I don't know.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions