What is the portable way to check whether malloc
failed to allocate non-zero memory block?
If the malloc function is unable to allocate the memory buffer, it returns NULL. Any normal program should check the pointers which the malloc function returns and properly handle the situation when the memory allocation failed.
malloc() normally fails today for one of two reason: (1) attempt to allocate more memory then is available, or (2) memory has been previously trashed (most common reason) such as buffer overflows and using uninitialized pointers (although there are a whole host of other causes).
You need to manage a list of all malloc() you have done with pointer + size. Then you can search for the size in that list, and decrement it in free(). You might have other possibilities to track memory, like: Valgrind with massif tool for tracking memory usage over time.
The same way you'd handle any failure without goto statements: avoid using goto statements! Really, what you need to decide is whether your program can continue after a malloc() failure. If it can't, just exit(), hopefully after providing information on why your program is exiting.
According to the Single Unix Specification, malloc
will return NULL
and set errno
when it fails.
I always do this:
tok = malloc( sizeof( char ) * ( strlen(tc) + 1 ) ); if( tok == NULL ) { /* Malloc failed, deal with it */ }
Some people do tok = (type) malloc( ... )
but you should cast the result because apparently it covers up some nasty errors. I will do some research and see if I can find out exactly what they are.
Edit:
Casting malloc can hide a missing #include <stdlib.h>
I found this link which contained a very good explanation:
http://cboard.cprogramming.com/faq-board/25799-faq-casting-malloc.html
"So when you say this (char*)malloc(10)
You're saying that you take whatever malloc returns, convert it to a char*, and assign that to the variable in question.
This is all well and good if malloc is prototyped properly (by including stdlib.h), where it's defined as returning void*.
The problem comes in when you fail to include stdlib.h, and the compiler initially assumes that malloc returns an int. The real problem is, you DONT get any warning from the compiler.
You merrily then convert that int to a char* (via the cast). On machines where sizeof(char*) is different from sizeof(int), the code is seriously broken.
Now if you just have char *var = malloc( 10 ); And you miss out the include , you will get a warning from the compiler."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With