←back to thread

237 points ekr____ | 4 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 #
1. PhilipRoman ◴[] No.42731676[source]
>checking the return of any allocation call

I would say this is pointless on many modern systems unless you also disable overcommit, since otherwise any memory access can result in a crash, which is impossible to check for explicitly.

replies(2): >>42732791 #>>42735066 #
2. kevin_thibedeau ◴[] No.42732791[source]
abort() isn't an option on all modern systems.
replies(1): >>42733767 #
3. josephg ◴[] No.42733767[source]
It’s an option on most systems.

Maybe not in embedded work - but in that case you might want to preallocate memory anyway.

4. lionkor ◴[] No.42735066[source]
Most code correctness is pointless until it isn't, yes