Re: Allocating too much memory kills my App rather than returning NULL
Re: Allocating too much memory kills my App rather than returning NULL
- Subject: Re: Allocating too much memory kills my App rather than returning NULL
- From: Martin Wierschin <email@hidden>
- Date: Thu, 10 Nov 2011 19:25:03 -0800
>> calloc() and malloc() are documented to return NULL when there isn't
>> enough memory to satisfy the user's request. Their implementation is
>> simply broken if they don't do that.
>
> Because calloc and malloc never return, they are not violating the spec.
>
> Nothing about the POSIX spec requires these functions to return. _If_
> they return, they must either return a suitably-aligned pointer or
> NULL (unless they were passed a size of 0, in which case the result is
> implementation-defined).
The documentation for malloc and friends isn't explicit about what happens when memory is exhausted, but a NULL return value is certainly implied:
> If there is an error, they return a NULL pointer and set errno to ENOMEM.
http://developer.apple.com/library/mac/#documentation/darwin/reference/manpages/man3/calloc.3.html
I understand the rationale in having the offending allocation trigger an immediate crash, so the backtrace shows the point of failure, instead of causing problems later on. That's great behavior for routine allocations like [[XXObject alloc] init], objc method caches, etc, where it would be onerous/impossible to write recovery code. But it would still be useful if there was a way to safely try a memory allocation, when you know beforehand that it is "large" (by whatever standard you're using), and you're willing to assume the burden of proper error checking and recovery.
~Martin
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden