简体   繁体   English

为什么&x + 1不会导致seg错误?

[英]Why won't &x + 1 cause seg fault?

In this thread , it uses &x + 1 to determine the size of some random struct x. 这个线程中 ,它使用&x + 1来确定一些随机struct x的大小。 I'm wondering why this is a legitimate solution? 我想知道为什么这是一个合法的解决方案? Will this ever cause a segmentation fault? 这会导致分段错误吗?

My understanding is as long as &x + 1 remains within the memory accessible to the current thread, it will be fine, but if &x + 1 somehow tries to access a piece of memory outside of its allowed range, it will cause seg fault, is that right? 我的理解是只要&x + 1保留在当前线程可访问的内存中,它就没问题,但如果&x + 1以某种方式尝试访问超出其允许范围的内存,则会导致seg错误,那对吗?

Third, the C standard explicitly allows pointers to point one past the end of an array. 第三,C标准明确允许指针指向一个超过数组末尾的指针。

...If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow ... ...如果指针操作数和结果都指向同一个数组对象的元素,或者指向数组对象的最后一个元素,则评估不应产生溢出...

And as @alk points out, when doing pointer arithmetic, a pointer to an object is treated like an array of length 1. 正如@alk指出的那样,在进行指针运算时,指向对象的指针被视为长度为1的数组。

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. 出于这些运算符的目的,指向不是数组元素的对象的指针与指向长度为1的数组的第一个元素的指针的行为相同,其中对象的类型为其元素类型。

(from sections 6.5.6.8 and 6.5.6.7 of the C99 draft here ) (从第6.5.6.8和C99草案6.5.6.7 这里

First, in C, all memory that is accessible by any thread is accessible by all threads. 首先,在C中,所有线程都可以访问任何线程都可访问的所有内存。 Threads are just not an issue here. 线程在这里不是问题。

Second, you never dereference the pointer &x + 1 , so you are not accessing any memory anyway. 其次,你永远不会取消引用指针&x + 1 ,所以你无论如何都不会访问任何内存。

So your code is correct. 所以你的代码是正确的。

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

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