Home > Blockchain >  C malloc failure
C malloc failure

Time:07-31

I've stumbled upon a problem of memory allocation. I am writing a simple application that is supposed to read files and get information from them. It is supposed to be very simple (single threaded) so I was wondering what should I do if malloc() or calloc() fails?

Should the function exit() the program with some error message or return NULL(or other appropriate return value) and try to allocate memory again?

CodePudding user response:

If malloc fails you basically have 3 options:

  1. free some memory and try again.
  2. don't allocate and do something else instead.
  3. exit the program.

assuming you needed the memory to store some data then 2 wouldn't be an option, and in that case you either do 1 or 3.

No one can predict all possible programs, but one reason I could see trying to allocate but not using memory was in a program where you were just testing to see how much you could allocate on a system under a given load.

Anyway I think 1 or 3 are probably most cases.

  • Related