-4

While learning C String, I had this code snippet:`

char s[1];
strcpy(s, "hello");
puts(s);
printf("sizeof(s) = %ld\n", sizeof(s));//the result is 1
printf("strlen(s) = %ld\n", strlen(s));//the result is 5
printf("s[4] = %c\n", s[4]);//print 'o'

Why do this code snippet have this strange result? I mean I can legally assign the string of length 5 to a string declared with size 1.

toantruong
  • 464
  • 1
  • 8
  • 16
  • 3
    Learn what **undefined behaviour** means! And C does not have a string type. `s` is an array. The rest is just convention. – too honest for this site Jul 18 '16 at 01:21
  • sizeof is the size of the char pointer (which is what the beginning of the string points to). `strlen` is a function that walks the string and calculates its length (as I understand it). – George Stocker Jul 18 '16 at 01:21
  • @GeorgeStocker: A C string is **no way** a pointer! It is an array. And `sizeof(s)` is exactly one of the differences between arrays and pointers! – too honest for this site Jul 18 '16 at 01:23
  • 2
    @GeorgeStocker Doesn't sizeof for a declared array (i.e., not one that's decayed to a pointer) return the size of the array? E.g., if it had been `char s[10]`, then sizeof(s) would have been 10 (because the declaration is still in scope, i.e., we haven't passed it somewhere else as a char* yet). – Joshua Taylor Jul 18 '16 at 01:25
  • @GeorgeStocker - `sizeof` returns the size of the array - i.e. one character. As to copying more data into this you are in undefined bevaiour – Ed Heal Jul 18 '16 at 01:26

1 Answers1

0

I mean I can legally assign the string of length 5 to a string declared with size 1.

No, you can't. You've written past the end of the buffer, which invokes undefined behavior. The code is erroneous, but the language standard places no requirements on the compiler to handle the situation in any particular way. The result can be anything from an immediate crash to garbled output to working exactly as expected. It all depends on what follows s in memory.

C does no bounds checking on array accesses; the language assumes you're smart enough not to access elements outside of the array bounds. It won't throw an exception if you read or write past the end of the array. As long as you don't clobber anything important, your code will appear to function normally.

John Bode
  • 119,563
  • 19
  • 122
  • 198