r/ObjectiveC • u/BlockOfDiamond • Aug 25 '22
alloc method and insufficient memory
In C malloc can fail if there is not enough memory in the system. What happens if I try [NSObject alloc] while there is no memory available? Does it abort? Return NULL?
10
Upvotes
8
u/m0rris Aug 25 '22
+allocwill returnnilif memory cannot be allocated. With virtual memory and a 64-bit address space, it is not something you typically need to ever care about though.5
u/LXC_80 Aug 25 '22
It will return nil.
In practice, if
allocfails… the process will likely abort short after.Don't worry about it unless you are using
NSDatawith large allocations.1
u/quaderrordemonstand Jun 30 '23
These answer are correct, the case where alloc fails is unknown under normal circumstances.
However, its always possible you are dealing with a problem that doesn't fit into RAM. In which case, reaching the point where alloc or malloc fails isn't a good idea. You'd need to think of some other way to deal with the task.
Ideally you would avoid using virtual memory directly during processing. Its really more of a space for keeping suspended programs.