sigmasternchen / Serwer

Standalone Webserver
MIT License
0 stars 0 forks source link

Checking return values of malloc/realloc #4

Closed BloodyWulf closed 7 years ago

BloodyWulf commented 7 years ago

Hey there.

I see that you never check the return values of malloc/realloc. Thats pretty bad! You must always check the return value of malloc/realloc. To not check that is realy careless.

malloc:

On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.

realloc

A pointer to the reallocated memory block, which may be either the same as ptr or a new location. The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.

C99/C11 (C++11)

A null-pointer indicates that the function failed to allocate storage, and thus the block pointed by ptr was not modified.

You also call malloc a few times with a value of zero. Thats also bad:

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

webserver.c, lines 289 headers.fields = (header_t*) malloc(0 * sizeof(header_t));

webserver.c, lines 384 server.handles = (handle_t*) malloc(0);

Maybe there are more occurrences of that. You should check that.

You should read also this articles from Ted Unangst: zero size objects it’s hard work printing nothing

Regards

sigmasternchen commented 7 years ago

I know that. This version is in general really bad coded.

On the matter of malloc(0): The reason is: How much space should be reserved for a dynamic array with size 0? I guess setting the pointer to NULL is better? realloc should (theoretically) deal with it.