简体   繁体   中英

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

In this thread , it uses &x + 1 to determine the size of some random 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?

Third, the C standard explicitly allows pointers to point one past the end of an array.

...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.

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.

(from sections 6.5.6.8 and 6.5.6.7 of the C99 draft here )

First, in C, all memory that is accessible by any thread is accessible by all threads. Threads are just not an issue here.

Second, you never dereference the pointer &x + 1 , so you are not accessing any memory anyway.

So your code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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