What is the portable way to check whether malloc
failed to allocate non-zero memory block?
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
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."