更新时间:2023-08-17 17:18:58
您是对的:它是不确定的行为,你不能指望它总是产生 0
You were right: it is undefined behavior and you cannot count it always producing 0
.
至于为什么要在这种情况下,看到零:现代操作系统中称为页相对粗粒度块是比单个变量(在x86至少4KB)大得多的内存分配给进程。当你有一个全局变量,它将位于某处的网页上。假设 A
的类型为 INT [] []
和 INT
是你的系统上的四个字节, A [27] [27]
将从年初位于大约500字节 A
。所以只要 A
靠近页的开头,访问 A [27] [27]
将被备份由实际存储器和读取也不会引起页面错误/访问冲突。
As for why you are seeing zero in this case: modern operating systems allocate memory to processes in relatively coarse-grained chunks called pages that are much larger than individual variables (at least 4KB on x86). When you have a single global variable, it will be located somewhere on a page. Assuming a
is of type int[][]
and int
s are four bytes on your system, a[27][27]
will be located about 500 bytes from the beginning of a
. So as long as a
is near the beginning of the page, accessing a[27][27]
will be backed by actual memory and reading it won't cause a page fault / access violation.
当然,你不能指望这个。如果,例如, A
是近4KB其他的全局变量pceded $ P $然后 A [27] [27]
将不会被存储备份,当你试着去读一下你的进程将会崩溃。
Of course, you cannot count on this. If, for example, a
is preceded by nearly 4KB of other global variables then a[27][27]
will not be backed by memory and your process will crash when you try to read it.
即使过程中不崩溃,你不能获得价值数 0
。如果你有一个现代化的多用户操作系统,它什么都不做一个非常简单的程序,但分配这个变量并打印该值时,你可能会看到 0
。操作系统设置存储器的内容时,交给了内存的过程,这样从一个进程或用户敏感数据不会泄露到其他一些良性的值(通常为全0)。
Even if the process does not crash, you cannot count on getting the value 0
. If you have a very simple program on a modern multi-user operating system that does nothing but allocate this variable and print that value, you probably will see 0
. Operating systems set memory contents to some benign value (usually all zeros) when handing over memory to a process so that sensitive data from one process or user cannot leak to another.
不过,有一个任意的存储器你读为零没有一般保证。你可以在这里存储上没有分配初始化的平台上运行您的程序,你会看到任何值发生在从上次使用是在那里。
However, there is no general guarantee that arbitrary memory you read will be zero. You could run your program on a platform where memory isn't initialized on allocation, and you would see whatever value happened to be there from its last use.
此外,如果 A
后面是被初始化为非零值,然后访问足够多的其他全局变量 A [27] [27]
会告诉你任何值恰好在那里。
Also, if a
is followed by enough other global variables that are initialized to non-zero values then accessing a[27][27]
would show you whatever value happens to be there.