A char
array and string are similar, but not the same.
In C,
A string is a contiguous sequence of characters terminated by and including the first null character. C11dr §7.1.1 1
void simple (char *bar) {
char MyArray[12];
strcpy(MyArray, bar);
}
My instructor says that MyArray
can copy at most 12 elements from bar,
This is correct: MyArray[]
can receive up to 12 characters.
strcpy()
copies the memory, starting at bar
to the array MyArray[]
and continues until it copies a null character. If more that 12 characters (the count of 12 includes the null character) are attempted to be copied, the result is undefined behavior (UB).
MyArray
can only store 11 characters
Not quite. MyArray[]
can store 12 characters. To treat that data as a string, a null character must be one of those 12. When interpreted as a string, the string include all the characters up to the null character. It also include the null chracter. Each element of MyArray[]
could be an 'x'
, but then that memory would not be a string as it lacks a null character.
So if the received value of bar
is 12 or greater, a buffer overflow would occur.
Not quite. If the strcpy()
attempts to write outside MyArray[]
, the result is undefined. Buffer overflow may occur. The program may stop, etc. The result is not defined. It is undefined behavior.
My instructor says that this will only happen if the received value of bar
is 13 or greater.
bar
is a pointer - it likely does not have a "value of 13". bar
likely points to memory that is a string. A string includes its terminating null character, so the string may consists of 12 non-null characters and a final null character for a total of 13 characters. MyArray[]
is insufficient to store a copy of that string.
Who's right?
I suspect the dis-connect is in the imprecise meaning of "bar
is 13"`. I see nothing the reported by the instructor as incorrect.