Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How detect malloc failure?

Tags:

c

What is the portable way to check whether malloc failed to allocate non-zero memory block?

like image 552
pic11 Avatar asked Jun 13 '11 01:06

pic11


People also ask

What happens when malloc fails?

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.

Why does malloc fail?

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).

How can I track my malloc?

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.

How do you handle a situation when malloc fails?

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.


2 Answers

According to the Single Unix Specification, malloc will return NULL and set errno when it fails.

like image 126
a3nm Avatar answered Oct 05 '22 15:10

a3nm


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."

like image 40
Swift Avatar answered Oct 05 '22 17:10

Swift