What is the simplest standard conform way to produce a Segfault in C?

后端 未结 10 1623
迷失自我
迷失自我 2020-11-29 21:59

I think the question says it all. An example covering most standards from C89 to C11 would be helpful. I though of this one, but I guess it is just undefined behaviour:

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 22:32

    Most of the answers to this question are talking around the key point, which is: The C standard does not include the concept of a segmentation fault. (Since C99 it includes the signal number SIGSEGV, but it does not define any circumstance where that signal is delivered, other than raise(SIGSEGV), which as discussed in other answers doesn't count.)

    Therefore, there is no "strictly conforming" program (i.e. program that uses only constructs whose behavior is fully defined by the C standard, alone) that is guaranteed to cause a segmentation fault.

    Segmentation faults are defined by a different standard, POSIX. This program is guaranteed to provoke either a segmentation fault, or the functionally equivalent "bus error" (SIGBUS), on any system that is fully conforming with POSIX.1-2008 including the Memory Protection and Advanced Realtime options, provided that the calls to sysconf, posix_memalign and mprotect succeed. My reading of C99 is that this program has implementation-defined (not undefined!) behavior considering only that standard, and therefore it is conforming but not strictly conforming.

    #define _XOPEN_SOURCE 700
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(void)
    {
        size_t pagesize = sysconf(_SC_PAGESIZE);
        if (pagesize == (size_t)-1) {
            fprintf(stderr, "sysconf: %s\n", strerror(errno));
            return 1;
        }
        void *page;
        int err = posix_memalign(&page, pagesize, pagesize);
        if (err || !page) {
            fprintf(stderr, "posix_memalign: %s\n", strerror(err));
            return 1;
        }
        if (mprotect(page, pagesize, PROT_NONE)) {
            fprintf(stderr, "mprotect: %s\n", strerror(errno));
            return 1;
        }
        *(long *)page = 0xDEADBEEF;
        return 0;
    }
    

提交回复
热议问题