In C, if I initialize a char array like this:
char lines[5];
memcpy((char *)line,"Hello",5)
Then if I execute the following expression:
line[6]='\0';
Would this cause buffer overflow? Thanks?
In C, if I initialize a char array like this:
char lines[5];
memcpy((char *)line,"Hello",5)
Then if I execute the following expression:
line[6]='\0';
Would this cause buffer overflow? Thanks?
Many problems. For one, why cast to char *
, when that is to what the array decays? Second, you need to use a zero-based index, not a one-based index; The first element of array a
is a[0]
not a[1]
.
Also you should have set the buffer size to 6, not 5, to make room for terminator
Then if I execute the following expression:
line[6]='\0';
Would this cause buffer overflow?
Yes. Because lines
contains five characters and you are overwriting the seventh one.
Would the comp[il]er assign 8 bytes for 'lines'?
No.
It might put 3 bytes of padding after lines
, in which case it's still a buffer overflow because lines
is still 5 bytes long.
You are definitely writing outside the bounds of the array, which leads to undefined behavior. The result could be any of the following:
Most platforms have alignment requirements such that there may be some unused bytes between the end of the array and the next object in memory1, and writing one or two bytes past the end of the array isn't much of an issue. But that's not the same thing as the compiler allocating "extra space" for the array.