malloc(0) 真的有效吗? [英] malloc(0) actually works?

查看:30
本文介绍了malloc(0) 真的有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
malloc(0) 有什么意义?

为什么 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
", str);

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

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

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

输出:

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

str 更短时,它就可以正常工作.

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

顺便说一句:为了编译,我使用了带有-D_FORTIY_SOURCE=0 -fno-stack-protector"的 GCC

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

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

推荐答案

为什么 malloc(0) 实际上返回一个有效的写入指针?

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

它不会返回一个有效的写入指针.它返回一个不使用的有效指针.或者它也可能返回 NULL,因为 C 标准将这种情况指定为实现定义.

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.

这篇关于malloc(0) 真的有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆