Q: What does malloc(0) do? What about free(NULL) ?
A: These seemingly simple questions have remarkably complex answers, especially if you generalize them to cover other Mac OS memory management APIs. Tables 1 and 2 list some commonly-used routines and their behavior in these cases.
Table 1. Allocating a block of zero bytes.
Routine
|
Platform
|
Returns |
malloc
|
ANSI C specification
|
either NULL or a pointer to a zero-length block |
malloc
|
Mac OS X System framework
|
a pointer to a zero-length block |
malloc |
CodeWarrior MSL |
NULL [1] [2] |
CFAllocatorAllocate |
all |
NULL [3] |
NewPtr |
all |
a pointer to a zero-length block |
NewHandle |
all |
a handle to a zero-length block |
MPAllocateAligned |
Mac OS X |
a pointer to a zero-length block |
MPAllocateAligned |
traditional Mac OS |
NULL |
OTAllocMem [InContext ] |
all |
a pointer to a zero-length block |
operator new [] |
ANSI C++ specification |
a pointer to a zero-length block |
operator new [] |
all |
a pointer to a zero-length block |
|
Table 2. Freeing a NULL pointer.
Routine
|
Platform
|
Behavior |
free
|
ANSI C specification
|
does nothing |
free |
all |
does nothing [1] |
CFAllocatorDeallocate
|
all
|
does nothing [4] |
DisposePtr |
Mac OS X |
sets MemErr to noErr |
DisposePtr |
traditional Mac OS, PowerPC |
sets MemErr to noErr |
DisposePtr |
traditional Mac OS, 68K |
illegal |
DisposeHandle |
Mac OS X |
sets MemErr to nilHandleErr |
DisposeHandle |
traditional Mac OS |
sets MemErr to noErr |
MPFree |
Mac OS X |
illegal [5] |
MPFree |
traditional Mac OS |
does nothing |
OTFreeMem |
all |
does nothing |
operator delete |
ANSI C++ specification |
does nothing |
operator delete |
all |
does nothing |
|
Notes:
- MSL information obtained from CodeWarrior Pro 8.3 MSL.
- You can alter this behavior by setting the
_MSL_MALLOC_0_RETURNS_NON_NULL compile-time variable and rebuilding MSL.
- This behavior is part of
CFAllocatorAllocate and is independent of the actual allocator used.
- This behavior is part of
CFAllocatorDeallocate and is independent of the actual allocator used.
- On current versions of Mac OS X (10.2 and earlier), this will not crash but instead print an a warning message to the console (r. 3227311).
[Apr 14, 2003]
|