what's the point in malloc(0)?

2018-12-31 20:28发布

Just saw this code:

artist = (char *) malloc(0);

and I was wondering why would one do this?

标签: c malloc
16条回答
高级女魔头
2楼-- · 2018-12-31 20:55

In Windows:

  • void *p = malloc(0); will allocate a zero-length buffer on the local heap. The pointer returned is a valid heap pointer.
  • malloc ultimately calls HeapAlloc using the default C runtime heap which then calls RtlAllocateHeap, etc.
  • free(p); uses HeapFree to free the 0-length buffer on the heap. Not freeing it would result in a memory leak.
查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 20:58

According to Reed Copsey answer and the man page of malloc , I wrote some examples to test. And I found out malloc(0) will always give it a unique value. See my example :

char *ptr;
if( (ptr = (char *) malloc(0)) == NULL )
    puts("Got a null pointer");
else
    puts("Got a valid pointer");

The output will be "Got a valid pointer", which means ptr is not null.

查看更多
妖精总统
4楼-- · 2018-12-31 21:00

Just to correct a false impression here:

artist = (char *) malloc(0); will never ever return NULL; it's not the same as artist = NULL;. Write a simple program and compare artist with NULL. if (artist == NULL) is false and if (artist) is true.

查看更多
忆尘夕之涩
5楼-- · 2018-12-31 21:04

Not sure, according to some random malloc source code I found, an input of 0 results in a return value of NULL. So it's a crazy way of setting the artist pointer to NULL.

http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html

查看更多
登录 后发表回答