eteran / c-vector

A dynamic array implementation in C similar to the one found in standard C++
MIT License
737 stars 109 forks source link

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

Closed andy5995 closed 2 years ago

andy5995 commented 2 years ago

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.

https://github.com/eteran/c-vector/blob/dbe15efb2ce065bc44342c152f7b330df30ac4ef/cvector.h#L73-L81

eteran commented 2 years ago

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.

andy5995 commented 2 years ago

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.