-1

So I'm learning C, I have experience with Java and Python, and this is a really curious thing which is happening.

When I run this code, the output is Hello7

#include <stdio.h>

int main()
{
    int a[1];
    a[1]=1;
    a[2]=2;
    a[3]=7;
    printf("Hello%d",a[3]);
}

But how is GCC able to print out Hello7 if the maximum size of the array is 1?

ChillBruh
  • 31
  • 3
  • 2
    It's an undefined behavior (https://en.wikipedia.org/wiki/Undefined_behavior) – Jack Jul 03 '15 at 21:02
  • Because the language does not trap limits in this case. This is Undefined Behaviour. If it happens to work because you access an array beyond its definition - it might not work yesterday. Happily for now, there is no obvious collision in the memory usage. – Weather Vane Jul 03 '15 at 21:02
  • @Paulpro I don't believe, could you please post a screenshot of your results? – Adam Stelmaszczyk Jul 03 '15 at 21:04
  • Not every piece of C code that is syntactically valid is a correct C program. In C nobody tells you that what you have isn't a valid program. – Kerrek SB Jul 03 '15 at 21:05
  • start with a textbook... – Jason Hu Jul 03 '15 at 21:06
  • 1
    I compiled and ran your program with MSVC. No compilation error. Correct output `Hello7` (even without a buffer flush from the absent `newline`). But it didn't exit, it just hung (crashed). Probably, because you overwrote the stack. – Weather Vane Jul 03 '15 at 21:10

1 Answers1

2

A C array is no more than a sequence of contiguous memory locations. When you ask C to give you a certain index from the array, it takes the start of the array and adds on the necessary number of bytes to get the the appropriate memory location. It doesn't know how big the array is supposed to be; in C that job is left to you as the programmer.

Sam
  • 8,330
  • 2
  • 26
  • 51