Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle realloc when it fails due to memory?

Tags:

Question says it all but here is an example:

typedef struct mutable_t{     int count, max;     void **data; } mutable_t;   void pushMutable(mutable_t *m, void *object) {     if(m->count == m->max){         m->max *= 2;         m->data = realloc(m->data, m->max * sizeof(void*));     }     // how to handle oom??     m->data[m->count++] = object; } 

How can I handle running out of memory and not NULL out all of my data?

edit - let's assume there is something which could be done e.g. free up some memory somewhere or at least tell the user "you can't do that - you're out of memory". Ideally I would like to leave what was allocated there.

like image 455
Nick Van Brunt Avatar asked Dec 31 '09 18:12

Nick Van Brunt


People also ask

What happens to memory if realloc fails?

Possible realloc() leak: when realloc() fails to allocate memory, original pointer is lost.

What does realloc return on failure?

realloc returns a void pointer to the reallocated (and possibly moved) memory block. If there is not enough available memory to expand the block to the given size, the original block is left unchanged, and NULL is returned.

Do you need to free memory after realloc?

In short, no. Once you call realloc() , you do not have to free() the memory addressed by pointer passed to realloc() - you have to free() the memory addressed by the pointer realloc() returns.

Does realloc erase memory?

No, the data will be copied for you into the new block that the returned p points at, before the old block is freed. This all happens before realloc returns, so the new p points to your data still.


2 Answers

The standard technique is to introduce a new variable to hold the return from realloc. You then only overwrite your input variable if it succeeds:

tmp = realloc(orig, newsize); if (tmp == NULL) {     // could not realloc, but orig still valid } else {     orig = tmp; } 
like image 161
R Samuel Klatchko Avatar answered Oct 22 '22 12:10

R Samuel Klatchko


This is a bit of a hot button topic as there are essentially 2 schools of thought on the subject

  1. Detect the OOM, and having the function return an error code.
  2. Detect the OOM and crash your process as fast as possible

Personally I am in camp #2. Expect for very special types of applications, OOM is fatal period. True, perfectly written code can handle an OOM but so few people understand how to write code that is safe in the face of no memory. Even fewer bother to actually do it because it's almost never worth the effort.

I dislike passing the error code off to the calling function for OOM's because it is the equivalent of telling the caller "I failed and there's nothing you can do about it". Instead I prefer to crash fast so the resulting dump is as instructive as possible.

like image 28
JaredPar Avatar answered Oct 22 '22 13:10

JaredPar