←back to thread

237 points ekr____ | 1 comments | | HN request time: 0.263s | source
Show context
bluetomcat ◴[] No.42724685[source]
This isn't proper usage of realloc:

    lines = realloc(lines, (num_lines + 1) * sizeof(char *));
In case it cannot service the reallocation and returns NULL, it will overwrite "lines" with NULL, but the memory that "lines" referred to is still there and needs to be either freed or used.

The proper way to call it would be:

    tmp = realloc(lines, (num_lines + 1) * sizeof(char *));

    if (tmp == NULL) {
        free(lines);
        lines = NULL;
        // ... possibly exit the program (without a memory leak)
    } else {
        lines = tmp;
    }
replies(9): >>42724759 #>>42724866 #>>42725435 #>>42726629 #>>42727024 #>>42728450 #>>42728785 #>>42729894 #>>42734023 #
o11c ◴[] No.42727024[source]
There's another bug, related to performance - this involves a quadratic amount of memory copying unless your environment can arrange for zero-copy.
replies(2): >>42728981 #>>42729917 #
1. ekr____ ◴[] No.42729917[source]
Author here. Quite so. See footnote 3:https://educatedguesswork.org/posts/memory-management-1/#fn3

"If you know you're going to be doing a lot of reallocation like this, many people will themselves overallocate, for instance by doubling the size of the buffer every time they are asked for more space than is available, thus reducing the number of times they need to actually reallocate. I've avoided this kind of trickery to keep this example simple."