Reputation: 358
Related to: C++ new int[0] -- will it allocate memory?
The standard says, in 5.3.4/7:
When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.
...and, in 3.7.3.1/2:
The effect of dereferencing a pointer returned as a request for zero size is undefined.
...yet, the pointer can't be a null pointer.
Since actually dereferencing the pointer is undefined behavior, does any implementation return a pointer to a guard page? I imagine that it'd be easy, and help detect bugs/improve security.
Upvotes: 9
Views: 471
Reputation: 3776
To track how much memory needs to be released most allocators I've looked within or wrote look something like:
void *malloc_example( size_t bytes ) { size_t *ret = get_memory(bytes + sizeof size_t); /* find free memory */ *ret = bytes; /* remember size of allocated area */ return (void *)( ret + 1 ); }
So when you allocate zero-length blocks you actually get a sneaky word ahead of the address returned to you. This also assures each allocation is assigned a unique address. This is important and pointing to dedicated guard memory for zero-length blocks is more of a waste as each free must test for what my experience says is a rare condition.
Some debugging allocators include additional overhead to catch double-frees, memory leaks, guard words to catch overflow of previous buffers, etc. Also, pointing to some magic memory can make such debugging more difficult to do.
Upvotes: 2
Reputation: 862
I looked at the (draft) standard and I couldn't find anything that explicitly prohibits this. I would guess that the answer is "no", though. This is why:
One possible implementation could be done by reserving a range of unpaged memory, and every time someone calls new int[0] it could return a different address in that range (easy to do if the allocator keeps a global counter or something like that).
On the plus side, you will gain the ability to immediately detect dereferences on this type of pointer. On the other hand, you will lose the ability to detect double-frees because delete on your pointer effectively becomes a no op, and you will make new and delete more complex and slower for all the normal cases.
So because it's tricky to do, and the cons outweigh the pros, I'm pretty confident that nobody does that.
gcc on linux just allocates a small amount of memory and returns that. I believe that this is pretty much a standard way to do this.
Upvotes: 4