我使用malloc(0)指向char的指针,并且我的代码有效.这是为什么? [英] I used malloc(0) for a pointer to char, and my code works. Why is that?

查看:73
本文介绍了我使用malloc(0)指向char的指针,并且我的代码有效.这是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个指向char的指针数组.我用malloc(0)为那些指针分配内存.

I created an array of pointers to char. I used malloc(0) to allocate memory for those pointers.

在那之后,我使用scanf()malloc(0分配的字节中恰好输入了一个字,就可以了.

After that, I used scanf() to enter exactly one word to the bytes allocated by malloc(0 and it worked.

那是为什么?

推荐答案

首先,来自 malloc()的手册页,(强调我的)

如果size为0,则malloc()返回NULL或唯一的指针值,该值随后可以成功传递给free() .

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

因此,不能保证malloc(0)始终返回NULL.因此,您的NULL检查可能不会成功.

So, it's not guaranteed that malloc(0) will return NULL, always. So, your NULL check may not be a success.

然后回答

那是为什么?

因为,如果malloc(0)返回的指针不是NULL,则只适合用作以后调用free()的参数时,别无其他.在您的情况下,您尝试将写入到内存中.这样做实际上是尝试写入无效的内存,该内存未分配给您的程序.这会调用未定义的行为.

because, in case malloc(0) returns a pointer other han NULL, it is only fit to be used as an argument to a later call to free(), nothing else. In your case, you're trying to write into the memory. Doing so is essentially attempt to write into an invalid memory, a memory which not allocated to your program. This invokes undefined behavior.

UB的真正的美是,有时,调用UB 的程序会出现 正常工作.

The real beauty of UB is that, sometimes, program invoking UB appear to work just fine.

这篇关于我使用malloc(0)指向char的指针,并且我的代码有效.这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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