0

Why can I store more than 3 characters in the array "char array[3]" ? For example, in this code:

#include <stdio.h>

char array[3];

main()
{
scanf("%s", array);
putchar(array[5]);
return 0;
}

You can enter a text of any length, and it will print the 6th letter. You can also print the entire text with "printf("%s", array). Why does this work although the array only has space for 3 characters?

Thomas
  • 13
  • 1
  • 4
    Lookup UNDEFINED BEHAVIOR – Charles Salvia Feb 14 '13 at 17:24
  • very similar to [why this code works in C](http://stackoverflow.com/questions/13897817/why-this-code-works-in-c) – netcoder Feb 14 '13 at 17:25
  • Surely this must be a duplicate? Perhaps look to close this type of question before providing multiple identical answers? – Eric J. Feb 14 '13 at 17:26
  • OT: You have to love questions that ask why something *works* rather than their too-often-requested counterparts: that which does *not*. – WhozCraig Feb 14 '13 at 17:27
  • Also, [why doesn't my program crash when I write past the end of an array?](http://stackoverflow.com/questions/6452959/why-doesnt-my-program-crash-when-i-write-past-the-end-of-an-array) – netcoder Feb 14 '13 at 17:32

3 Answers3

3

Your code is able to print the entire word because it has not been overwritten yet. You are setting the memory and then immediately reading from it. If you were to attempt to read from that memory location later in your program's execution, you may get an entirely different result.

This is undefined behavior... and in your case, it printed the "correct" output.

Inisheer
  • 20,376
  • 9
  • 50
  • 82
1

array is defined to be a global array and hence would typically be a part of .bss section. Since the .bss section of your system has sufficient memory, you are able to write into the same. Clearly this is a violation which will get caught when you exceed the size of this section.

Ganesh
  • 5,880
  • 2
  • 36
  • 54
0

Because of the way scanf() works, it will just keep writing into memory what is sent to it. Because you're reading right after writing, the extra memory used by the array hasn't been overwritten yet, so you can read the entire string back.
There are other functions in C which will limit your input, such as fgets().

Vitor M. Barbosa
  • 3,286
  • 1
  • 24
  • 36