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

后端 未结 10 1637
迷失自我
迷失自我 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:38

    It's hard to define a method to segmentation fault a program on undefined platforms. A segmentation fault is a loose term that is not defined for all platforms (eg. simple small computers).

    Considering only the operating systems that support processes, processes can receive notification that a segmentation fault occurred.

    Further, limiting operating systems to 'unix like' OSes, a reliable method for a process to receive a SIGSEGV signal is kill(getpid(),SIGSEGV)

    As is the case in most cross platform problems, each platform may (an usually does) have a different definition of seg-faulting.

    But to be practical, current mac, lin and win OSes will segfault on

    *(int*)0 = 0;
    

    Further, it's not bad behaviour to cause a segfault. Some implementations of assert() cause a SIGSEGV signal which might produce a core file. Very useful when you need to autopsy.

    What's worse than causing a segfault is hiding it:

    try
    {
         anyfunc();
    }
    catch (...) 
    {
         printf("?\n");
    }
    

    which hides the origin of an error and all you've got to go on is:

    ?
    

    .

提交回复
热议问题