[英]why can I write over a piece of memory which has been allocated 0 space?
Why is it that I allocate a space of size 0 to array but i can still write over that piece of memory? 为什么我将大小为0的空间分配给数组但我仍然可以写入那段内存?
#include<stdio.h>
int main(int argc, char** argv)
{
int * array = malloc((sizeof(int)) * 0);
int i;
for(i = 0; i < 10; i++)
array[i] = i;
for(i = 0; i < 10; i++)
printf("%d ", array[i]);
}
You code invokes undefined behaviour as you access index out of bounds - 您访问索引越界时代码调用未定义的行为 -
for(i = 0; i < 10; i++)
array[i] = i;
You won't get any warning or error about such thing but this is documented in standards that it is UB . 您不会收到有关此类事情的任何警告或错误,但这是在UB的标准中记录的。
And in that case output could be anything. 在这种情况下,输出可以是任何东西。
And for this line - 而对于这一行 -
int * array = malloc((sizeof(int)) * 0);
C Standard says - C标准说 -
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.
如果请求的空间大小为零,则行为是实现定义的:返回空指针,或者行为就像大小是非零值一样,但返回的指针不应用于访问对象。
Here it's return may or may not be NULL pointer
. 这里它的返回可能是也可能不是
NULL pointer
。 But it is clear that this pointer should not be used to access any object. 但很明显,这个指针不应该用于访问任何对象。
malloc
with an argument of 0
returns either NULL
or a unique pointer that can be passed to free
. 参数为
0
malloc
返回NULL
或可以传递给free
的唯一指针。 If it does return a non-null value and that pointer points to memory that's within a page that's valid for your program and writable, the operating system won't zap you if you try to write to it, but you might end up rewriting some parts of your program's data (=> undefined behavior). 如果它确实返回一个非null值,并且该指针指向一个对你的程序有效并且可写的页面内的内存,那么如果你试图写入它,操作系统将不会摧毁你,但你最终可能会重写一些程序数据的一部分(=>未定义的行为)。
C is an unsafe language . C是一种不安全的语言 。 as an unsafe language it allows you to do risky actions as the following:
作为一种不安全的语言,它允许您执行以下有风险的操作:
void*
to other types and vica versa). void*
为其他类型,反之亦然)。 Unmanaged
. Unmanaged
。 Since those actions are risky and might lead to Memory Leak
, Memory Corruption
and other unwanted results, you should avoid doing such things when they are not neccesary and keep clean and conventioned code (make this 10
a constant and avoid working on unallocated memory ). 由于这些操作存在风险并且可能导致
Memory Leak
, Memory Corruption
和其他不需要的结果,因此您应该避免在不需要时执行此类操作并保持干净和常规代码(使此10
保持不变并避免处理未分配的内存 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.