简体   繁体   中英

When is a segmentation fault guaranteed?

I'm learning c++ and I've learned that segfaults can happen because of undefined behaviour. Are there ever cases though, where segfaults are guaranteed to happen? Or is it always undefined behaviour?

Segfaults occur in an operating system with memory protection when you attempt to read or write memory that you do not have permission to access — special values like nullptr , memory reserved for the OS, or memory of another process.

Because segfaults are raised by the OS, they are an inherently platform-specific concept. Something that causes a segfault on Windows will not necessarily cause a segfault on eg AmigaOS. The C++ standard, being platform-agnostic, doesn't even mention segfaults.

On modern OSes with memory protection, you can always be assured a segfault when you access memory that you don't own. Dereferencing nullptr will cause it for sure. Accessing a random address is probably not within your process's address space, so that will likely cause a segfault (hence why accessing uninitialized pointers or dangling pointers often causes a segfault). On AmigaOS or classic Mac OS, which lack memory protection, you won't get a segfault from accessing random pointers. Instead, you could overwrite the memory of the OS or another process (which would likely be disastrous).

Basically, a segfault is an OS concept, not a C++ concept, so what you can do to cause one in C++ depends on what you're running on.

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