malloc的行为(0) [英] behaviour of malloc(0)

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

问题描述

  INT的main()
{
    字符* P;
    P =(字符*)malloc的(的sizeof(char)的* 0);
    的printf(你好输入数据,而无需空格:\\ n);
    scanf的(%S,P);
    的printf(输入的字符串为%s \\ n,p)的;
    //看跌(P);
}

在编制以上code和运行它,该程序能够读取字符串,即使我们分配了一个0字节内存的指针p

实际发生在声明什么 P =(字符*)malloc的(0)


解决方案

是实现定义的

什么的malloc()将返回,但它是不确定的行为,以便使用该指针。和未定义的行为意味着什么都可以从字面上程序不工作故障发生崩溃,所有的安全的赌注都关闭。

C99标准:

7.22.3内存管理功能结果
第1段:


  

如果该空间的请求的大小是零,该行为是实现定义:无论是空指针被返回,或者行为好像大小是一些非零值,不同的是返回指针不应被用来访问对象。


int main()
{
    char *p;
    p = (char* ) malloc(sizeof(char) * 0);
    printf("Hello Enter the data without spaces :\n");
    scanf("%s",p);
    printf("The entered string is %s\n",p);
    //puts(p);
}

On compiling the above code and running it , the program is able to read the string even though we assigned a 0 byte memory to the pointer p .

What actually happens in the statement p = (char* ) malloc(0) ?

解决方案

It is implementation defined what malloc() will return but it is undefined behavior to use that pointer. And Undefined behavior means that anything can happen literally from program working without glitch to a crash, all safe bets are off.

C99 Standard:

7.22.3 Memory management functions
Para 1:

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.

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

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