Search code examples
cgccbuffer-overflow

Why this c code below works fine? (C Basic, Buffer overflow test)


#include <stdio.h>

int main(int argc, char *argv[])
{
    int arr[5] = {1, 2, 3, 4, 5};
    arr[6] = 7; // [1, 2, 3, 4, 5, 6]
    
    printf("arr[6] = %d\n", arr[6]);

    return 0;
}

As I recall, it used to give a warning message when compiling and an unknown value when running. (Or I could see a Segment Fault message).

So I would like to know from which version the code above started working correctly.

My current GCC version is as follows:

gcc-13 (Homebrew GCC 13.2.0) 13.2.0
Copyright (C) 2023 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Solution

  • Your use of "working correctly" is wrong. For something to be working correctly, there would have to be a definition of what the correct behavior is - but there is none and the code has undefined behavior in all versions.

    That means that the program could crash, print "hello world", stall or do pretty much anything, including printing arr[6] = 7, which is no more correct than any other behavior.