的malloc(0)的实际工作? [英] malloc(0) actually works?

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

问题描述


  

可能重复:结果
  什么是在malloc的点(0)?


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

 的char *海峡= NULL;海峡=(字符*)malloc的(0); //分配0字节?的printf(str的指针:%P \\ N,STR);的strcpy(STR,一个很长的字符串...................);的printf(str的值:%S,STR);免费(STR); //导致崩溃如果str太长

输出:

  str的指针:0xa9d010
中止
str的值:一个很长的字符串...................

STR 短则它只是工作,因为它应该。

BTW:对于编译我用GCC与-D_FORTIY_SOURCE = 0 -fno堆栈保护器

  *** glibc的检测*** ..:免费():无效的下一个尺寸(快):0x0000000000a9d010 ***


解决方案

  

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


它不会写入返回一个有效的指针。它返回一个有效的指针的不使用的它。或者,它可能会返回 NULL ,以及因为C标准规定这种情况下,要实现定义的。

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 ***

解决方案

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.

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

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