malloc(0) actually works? [duplicate]

2019-01-15 23:14发布

Possible Duplicate:
what’s the point in malloc(0)?

Why does malloc(0) actually return a valid pointer for writing ?

char *str = NULL;

str = (char*)malloc(0); // allocate 0 bytes ?

printf("Pointer of str: %p\n", str);

strcpy(str, "A very long string ...................");

printf("Value of str: %s", str);

free(str); // Causes crash if str is too long

Output:

Pointer of str: 0xa9d010
Aborted
Value of str: A very long string ...................

When str is shorter then it just works as it should.

BTW: For compiling I used GCC with "-D_FORTIY_SOURCE=0 -fno-stack-protector"

*** glibc detected *** ..: free(): invalid next size (fast): 0x0000000000a9d010 ***

3条回答
疯言疯语
2楼-- · 2019-01-15 23:50

malloc() is supposed to return a void* pointer. And it faithfully does that. But leads to UB when you dereference it.

查看更多
走好不送
3楼-- · 2019-01-15 23:59

It is undefined behavior to dereference the pointer returned by malloc(0).

From the C Standard:

(C99, 7.20.3p1) "If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object."

查看更多
走好不送
4楼-- · 2019-01-16 00:05

Why does malloc(0) actually return a valid pointer for writing?

It doesn't return a valid pointer for writing. It returns a valid pointer for not using it. Or it may return NULL as well since the C standard specifies this case to be implementation defined.

查看更多
登录 后发表回答