Search code examples
cmemory-managementbuffer-overflow

Why am I able to copy more bytes than defined in the char array?


I have the following code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char buffer[2];
    strcpy(buffer, "12345678910");
    printf("%s\n", buffer);
    return 0;
}

Since, I have already defined the char array with size 2, I shouldn't be able to put in more than 2 char plus null terminating character. Yet, it is able to take more than that without any buffer overflows or segmentation faults. Even if I copy the string strcpy(buffer, "123456789101298362936129736129369182");, it works fine. The error is generated when I push strcpy(buffer, "1234567891012983629361297361293691823691823869182632918263918");.

More of a theroetical question than a practical, but I hope it helps the new and the experienced programmers alike since it talks about the fundamentals, and helps improving coding ethics. Thanks in advance.


Solution

  • The simple answer is that C does not protect you from yourself. It's YOUR responsibility to check boundaries. The program will happily read and write wherever you instruct it to. However, the operating system may say something if you do this, which is usually a "segmentation fault". A worse scenario is that it may overwrite other variables.

    This is a source of many bugs in C, so be careful. Whenever you're writing outside outside a buffer, you're invoking undefined behavior and these can manifest themselves in various ways, including the program working as it should, overwriting variables and segmentation faults.

    I shouldn't be able to put in more than 2 char plus null terminating character

    This is a common bug. It's NOT "plus null terminating character". It's INCLUDING null terminating character.