Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

c - Why does malloc(0) return a non-null address in Windows?

The code below returns an address when executed in Windows, though I was expecting it to return NULL.

int main()
{
   char *ptr = NULL;
   ptr = malloc(0);
   printf("malloc returned = %u
", ptr);

}

What could have prompted such an implementation of malloc? Is there any reason behind it?

Since, this is a 0 byte memory, I didn't experiment writing any data. But, can this memory be used for anything at all?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's just the minimum size you're requesting. And since there are no zero-length blocks in the Win32 heap, you can:

void *p = malloc(0);
// ... do some stuff in between...
realloc(p, n);

Which should mostly result in reusing a block of the heap (if you're lucky and the new size is small). A minor opportunist optimization (or a slow-down, depending on the context and blood coffee-levels).

This is a simplified example. The actual situation could be a class that allocates a buffer when it's created and also allows to grow it. If the inputs are annoying to control, you could just let it do that zero-sized buffer allocation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...