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

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

问题描述

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

在编译并运行上面的代码后,即使我们为指针 p 分配了一个 0 字节的内存,程序也能够读取字符串.

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 .

语句 p = (char* ) malloc(0) 中实际发生了什么?

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

推荐答案

malloc() 将返回什么是实现定义的,但使用该指针是未定义的行为.未定义行为意味着任何事情都可能发生,从程序无故障运行到崩溃,所有安全赌注都已关闭.

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 标准:

7.22.3 内存管理功能
第 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天全站免登陆