Can a C/C++ program seg-fault from reading past the end of an array (UNIX)?

后端 未结 3 576
野趣味
野趣味 2021-01-18 02:33

I\'m aware that you can read past the end of an array - I\'m wondering now if you can seg-fault just by performing that reading operation though.

int someint         


        
相关标签:
3条回答
  • 2021-01-18 02:43

    This is undefined behaviour and entirely depends on the virtual memory layout the operating system has arranged for the process. Generally you can either:

    • access some gibberish that belongs to your virtual address space but has a meaningless value, or
    • attempt to access a restricted memory address in which case the memory mapping hardware invokes a page fault and the OS decides whether to spank your process or allocate more memory.

    If someints is an array on the stack and is the last variable declared, you will most likely get some gibberish off the top of the stack or (very unlikely) invoke a page fault that could either let the OS resize the stack or kill your process with a SIGSEGV.

    Imagine you declare a single int right after your array:

    int someints[100];
    int on_top_of_stack = 42;
    std::cerr << someints[100] << std::endl;
    

    Then most likely the program should print 42, unless the compiler somehow rearranges the order of declarations on the stack.

    0 讨论(0)
  • 2021-01-18 03:00

    Yes, it can segfault if memory at that address is not accessible by the program. In your case it is not likely as array is allocated on stack and is only 100 bytes long and stack size is significantly larger (i.e. 8 MB per thread on Linux 2.4.X), so there will be uninitialized data. But in some cases it may crash. In either case, this code is erroneous and profilers like Valgrind should be able to help you troubleshoot it.

    0 讨论(0)
  • 2021-01-18 03:00

    The second line can cause literally anything to happen and still be correct as far as the language specification is concerned. It could print gibberish, it could crash due to a segmentation fault or something else, it could cause power to go out on the entire eastern seaboard, or it could cause the canonical demons to fly out of your nose...

    That's the magic of undefined behaviour.

    0 讨论(0)
提交回复
热议问题