简体   繁体   English

什么机制检测未分配内存的访问?

[英]What mechanism detects accesses of unallocated memory?

From time to time, I'll have an off-by-one error like the following: 有时,我会有一个像以下一样的错误:

unsigned int* x = calloc(2000, sizeof(unsigned int));

printf("%d", x[2000]);

I've gone beyond the end of the allocated region, so I get an EXC_BAD_ACCESS signal at runtime. 我已超出分配区域的末尾,因此我在运行时获得了EXC_BAD_ACCESS信号。 My question is: how is this detected? 我的问题是:这是如何被发现的? It seems like this would just silently return garbage, since I'm only off by one byte and not, say, a full page. 看起来这只会默默地返回垃圾,因为我只关闭了一个字节,而不是整页。 What part of the system prevents me from just returning the garbage byte at x + 2000 ? 系统的哪个部分阻止我在x + 2000处返回垃圾字节?

The memory system has sentinel values at the beginning and end of its memory fields, beyond your allocated bytes. 内存系统在其内存字段的开头和结尾都有标记值,超出了分配的字节数。 When you free the memory, it checks to see if those values are intact. 释放内存时,它会检查这些值是否完好无损。 If not, it tells you. 如果没有,它告诉你。

Perhaps you are just lucky because you are using 2000 as a size. 也许你只是幸运,因为你使用2000作为一个大小。 Depending on the size of int the total size is divisible by 32 or 64 , so chances are high that the end of it really terminates the "real" allocation. 根据int的大小,总大小可以被3264整除,因此很有可能它的结尾真正终止了“真正的”分配。 Try with some odd number of bytes (better use a char array for that) and see if your systems still detects it. 尝试使用奇数个字节(最好使用char数组)并查看您的系统是否仍然检测到它。

In any case you shouldn't rely on finding these bugs this way. 无论如何,你不应该依赖这种方式来发现这些错误。 Always use valgrind or similar to check your memory accesses. 始终使用valgrind或类似方法检查您的内存访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM