user3796261
user3796261

Reputation: 751

can I loop malloc on failure?

I'm doing some networking C code and I don't want to exit the program if I'm out of memory, and I don't want to ignore a clients data that he's sent me. So I was thinking I would do something like this

while(1){
    client_packet = (struct packet_data *)malloc(size);
    if(client_packet != NULL){
        break;
    }
    if(errno == ENOMEM){
        sleep(1);
        continue;
    }else{
        return;
    }
}

Keep in mind this is run from a child process that's been forked off. I'm gonna have as many child processes as possible when the program is in full swing. So my logic is that chances are that if I didn't have memory when I made the call to malloc, sleep for a second to give other processes a chance to call free, then try again.

I can't really test this myself until I have a situation where I might run out of memory, but would this concept be effective?

Upvotes: 1

Views: 178

Answers (2)

Long_GM
Long_GM

Reputation: 191

Typically, failure of malloc happens when the memory request can not be satisfied because there is not a usable block of memory. Looping of malloc may solve the problem although it completely depends on specific situations.

For instance, there are 2 processes running simultaneously on your computer, the first one requests too much dynamic memory that leads to the failure of the second process malloc(). While looping for malloc() in the second process, the first one starts to release their allocated memory via free() (the operation is switch frequently between processes by OS scheduler), now the malloc() in the second process will return a successful pointer.

However, I don't think this implementation is a good idea since this loop can block forever. Furthermore, looping like this is CPU consuming.

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

It depends on the computer and the operating system that you are using, but usually this will be just pointless.

Lots of software nowadays is 64 bit. That means in practice that malloc will never fail, unless your size argument is ridiculously wrong, like an uninitialised variable, or (size_t) -1 which happens to be about 17 billion Gigabyte. What happens is that your application will start swapping like mad if you exceed the available RAM, and at some point the user can't take the slowness anymore and kills your application. So even checks for malloc failure are often pointless as long as you make sure your app crashes if it fails and doesn't go off doing stupid things, for security reasons.

As an example of code seriously using this approach, take MacOS X / iOS code, where many essential functions have no way to notify you if they run out of memory.

Now if you have a situation where you can't find the memory to allocate a small data packet, what are the chances of the application as a whole surviving this and doing anything meaningful? Nil?

Upvotes: 1

Related Questions