0

If I allocate a char array with size of 4 and then input 4 characters via scanf. The program works, but why? AFAIK, you need extra one space for null terminator, right? If I input 5 characters, it starts to show some errors:

*** stack smashing detected ***: <unknown> terminated
Aborted.
int main(int argc, char const *argv[])
{
    char buffer[4];
    scanf("%s", buffer);
    printf("%s %d", buffer, strlen(buffer));
    return 0;
}
user762750
  • 159
  • 7
  • These things are never exact. It's not guaranteed that you'll get an immediately-visible error when you ask `scanf` to store 5 characters into an array of size 4 -- but that obviously doesn't mean it's okay, either. – Steve Summit Jun 15 '19 at 11:32
  • @SteveSummit Thank for the reply, but I would like to know why this works? – user762750 Jun 15 '19 at 11:34
  • 2
    It's kind of like asking, "I was driving down the road. The speed limit was 55 miles per hour. I drove 56 miles per hour, and nothing happened. Then I sped up to 57 miles per hour, and a policeman pulled me over and warned me. Why?" – Steve Summit Jun 15 '19 at 11:36
  • 1
    When you write more to an array than it's defined to hold (or, as in this case, when you ask a library function to do it for you), the results will depend on what's in that other memory, the memory off beyond the end of your array, the memory you weren't supposed to write to. If no other part of your program is using that memory, or if no other part of your program cares, you might be able to "get away with it". (Or you might not.) – Steve Summit Jun 15 '19 at 11:39
  • See also [this long answer](https://stackoverflow.com/questions/37087286/c-program-crashes-when-adding-an-extra-int/37087465#37087465) to a sort-of similar question. – Steve Summit Jun 15 '19 at 11:42
  • `printf("%s %d", buffer, strlen(buffer));` -> `printf("%s %zu\n", buffer, strlen(buffer));` – chqrlie Jun 15 '19 at 11:43

1 Answers1

1

This is undefined behavior which means that anything may happen. I this case the most likely scenarios are either working as it should or that it crashes with a segfault or something else that is related to memory access.

And yes, you need one extra byte for the null terminator.

klutt
  • 30,332
  • 17
  • 55
  • 95