Comment by astrobe_
2 days ago
The program abort()s if the reallocation fails. But indeed, for an educational example, it's not good to be too smart.
I believe the test if(!num_lines) is unnecessary, because reallocating a NULL pointer is equivalent to malloc(). This is also a bit "smart", but I think it is also more correct because you don't use the value of one variable (num_lines is 0) to infer the value of another (lines is NULL).
To go further, an opened-ended structure like:
struct
{
unsigned count;
char* lines[];
};
... could also be preferable in practice. But actually writing good C is not the topic of TFA.
> I believe the test if(!num_lines) is unnecessary, because reallocating a NULL pointer is equivalent to malloc().
I thought that this behaviour was deprecated in C23, but according to cop reference it is still there[0].
An I thinking of realloc with 0 size or was this actually a thing that was discussed?
[0] https://en.cppreference.com/w/c/memory/realloc
Section 7.24.3.7 The realloc function
https://open-std.org/jtc1/sc22/wg14/www/docs/n3096.pdf
> If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, or if the size is zero, the behavior is undefined. If memory for the new object is not allocated, the old object is not deallocated and its value is unchanged.