eteran / c-vector

A dynamic array implementation in C similar to the one found in standard C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Shouldn't an error code or NULL be returned if malloc or realloc fails?

andy5995 opened this issue · comments

Shouldn't an error code or NULL be returned if malloc or realloc fails? It seems that if those two calls ever return NULL, the program will either just exit, or if NDEBUG is defined, assert won't do anything.

c-vector/cvector.h

Lines 73 to 81 in dbe15ef

size_t *cv_p = malloc(cv_sz); \
assert(cv_p); \
(vec) = (void *)(&cv_p[2]); \
cvector_set_capacity((vec), (count)); \
cvector_set_size((vec), 0); \
} else { \
size_t *cv_p1 = &((size_t *)(vec))[-2]; \
size_t *cv_p2 = realloc(cv_p1, (cv_sz)); \
assert(cv_p2); \

It's kind of a design choice. There's a strong argument for "if you don't have enough RAM available to malloc, then there's not much you can do besides exit the program".

Additionally, as a fun fact, on many OSes like Linux, malloc will NEVER return NULL! They will happily reserve more virtual address space than they can possibly provide RAM for, and will simply crash later when you try to actually use the memory by reading or writing it.

Additionally, as a fun fact, on many OSes like Linux, malloc will NEVER return NULL! They will happily reserve more virtual address space than they can possibly provide RAM for, and will simply crash later when you try to actually use the memory by reading or writing it.

I see. Thanks for the explanation.