←back to thread

237 points ekr____ | 1 comments | | HN request time: 0s | 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 #
lionkor ◴[] No.42724759[source]
Very odd that an article trying to teach memory management would miss this, this should be common knowledge to anyone who used realloc, just like checking the return of any allocation call.
replies(2): >>42725040 #>>42731676 #
bluetomcat ◴[] No.42725040[source]
They treat an OOM situation as exceptional and immediately call abort() in case any allocation function returns NULL. The specification of these functions allows you to handle OOM situations gracefully.
replies(1): >>42733750 #
josephg ◴[] No.42733750[source]
> The specification of these functions allows you to handle OOM situations gracefully.

In theory, sure. But vanishingly little software actually deals with OOM gracefully. What do you do? Almost any interaction with the user may result in more memory allocations in turn - which presumably may also fail. It’s hard to even test OOM on modern systems because of OS disk page caching.

Honestly, panicking on OOM is a totally reasonable default for most modern application software. In languages like rust, this behaviour is baked in.

replies(1): >>42734041 #
1. tptacek ◴[] No.42734041[source]
I agree. The fact that Rust and Go will panic by default in this situation is pretty close to dispositive on what the right thing to do in (most) C code is.