How does segmentation fault work internally?


  • 1
    F

    In segfault.c:

    void
    main()
    {
        int *p = NULL;
    
        *p = 10;
    }
    

    Obviously a segmentation fault will occur when running above program. A message will be printed out:

    # ./segfault
    Segmentation Fault
    #

    How does segmentation fault work internally? what prints the message "Segmentation Fault"?


  • 0
    V

    In case of invalid access to memory SIGSEGV signal get triggered which internally prints the msg.


  • 25
    F
    1. How does segmentation fault work internally?

    When a processor is given a virtual address, it passes the address to MMU which will check if there is a mapping from the virtual address to physical address by looking up the page table (MMU will check TLB first though ). If there is no such mapping, the processor will take it as a page fault and subsequently check the page fault is a valid or not by checking if the address belongs to any segments the process currently has.

    When the page fault is valid, which means the page resides in the swap space and needs to be swapped into memory, the processor will proceed after the page gets swapped in; otherwise, the page fault is invalid, the processor will send a segmentation fault signal to the process and kills the process by default if there is no signal handler that catches the SIGSEGV signal.

    1. What prints the message "Segmentation Fault"?

    Shell that runs the program prints the message "Segmentation Fault". Basically when the process is killed because of segmentation fault, its parent(the shell in this case) that calls wait() to wait for its termination will get its exit status. Then the parent knows the reason why the child process is terminated based on the exit status, and prints the message accordingly.


  • 0
    S

    When the processor makes a virtual memory reference, the virtual address is passed to the TLB for translation. If the translation is present but process lacks the permissions to access that address, the processors halts the process and raises a SIGSEGV signal that captured by the kernel. The kernel terminates the process and passes a SIGSEGV to the parent !
    If the virtual address is absent, the hardware page table walker walks the process's page table. Irrespective of where the page resides, whether in swap or memory, if the walker does not find the virtual address in the page table, it will raise a SIGSEGV. And the rest is history !


  • 0
    F
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.