First of all, this is incorrect and actually does the opposite of what it should:
void *p;
p = malloc(100);
if (p)
{
perror("malloc");
return false;
}
This if statement says: if( malloc succeeded ){ return AN_ERROR; }
It should say:
void *p;
p = malloc(100);
if( NULL == p )
{
perror("malloc");
return false;
}
Now as for your question:
But one thought, why do it if you can guarantee getting memory?
As Gopi stated, you cannot guarantee getting memory. You very well can run out of memory and thus be unable to allocate anymore. It is unlikely that you will use up all of the available memory for the process, but it could happen. This is why checking the return of functions like like malloc()
, calloc()
, and realloc()
is essential.
Any of these memory allocation functions can fail if there is not enough memory and you must be prepared to handle that. Let us suppose you allocate space for string, but malloc fails and you do not check for that:
int main(int argc, char *argv[]){
char stringToCopy[] = "Some very long string would be here ...";
char *stringBuffer = malloc( 1000 ); // 1000 char buffer
// Malloc failed and we did not check for it
strncpy(stringBuffer, stringToCopy); /* UNDEFINED BEHAVIOUR */
return 0;
}
So in this situation, malloc failed and we proceeded to attempt to copy the string to the buffer anyway. As soon as we begin doing that, we cause undefined behavior. Typically this kind of action would cause the program to crash due to a Segmentation Fault.
This can be serious and can result in the loss of data or the loss of service. At a minimum, a segmentation fault would inconvenience the user.
As some general rules: Always check the return values of malloc()
, calloc()
and realloc()
; Never blindly trust that these functions were successful.
Whether you choose to do this check inside of a macro or not is your own choice (there aren't many advantages/disadvantages), but just make sure you perform the check and you perform it properly.