Reputation: 23
I was learning the basics of C programming , and I wanted to test some lines for strings.
This is my code:
int main(){
char a[] = "abc";
strcpy(a,"pqrst");
printf("%s; %d",a, sizeof(a));
}
I expected the code to output size=6 (p, q, r, s, t and '\0'), but instead, it still prints size=4. How does this work?
Upvotes: 2
Views: 480
Reputation: 45704
Your strcpy
-call has a buffer-overrun (the source is two byte longer than the destination), leading to undefined behavior (UB).
Invoking UB means there's nothing left to reason about, on any execution path invoking it (that includes all paths here), even before you get to it.
If you fix the UB, sizeof
is evaluated at compile-time for all but VLAs, giving size of the argument: Array of (3 elements "abc" + 1 implicit terminator "\0") char
.
Upvotes: 1
Reputation: 80355
sizeof(a)
is evaluated at compile-time. The type of a
, partially determined from the char a[]
part of the declaration and partially from the "abc"
initializer, is “array of 4 chars”, therefore sizeof(a)
evaluates to 4
. The value of the elements of a
have no influence on the result.
Incidentally, the strcpy
call in your program causes a buffer overflow. Extra characters are written somewhere in memory and may cause unpredictable behavior.
If you copied the string "z" to a
with strcpy(a, "z");
, there would be no undefined behavior, strlen(a)
would then evaluate to 1
, but sizeof(a)
would still be 4
.
Upvotes: 3
Reputation: 2143
sizeof is computed at compile time, based on the declaration of a
, which has 4 characters (3 + 1 null terminator). It should be noted sizeof an array and length of the string in an array aren't the same thing.
Moreover, the copy has overflowed the buffer. You have to create a large enough array to hold the string you want to copy over.
Upvotes: 4
Reputation: 82006
This line
char a[] = "abc";
creates space on the stack for a string of 4 characters. It's the same as doing:
char a[4] = "abc";
When you do:
strcpy(a, "pqrst");
It basically does:
int len = strlen("pqrst") + 1;
for (int i=0; i<len; ++i)
a[i] = "pqrst"[i];
Clearly, that code will overwrite the bounds of the a
array.
Basically though, it sounds like you're expecting C to do extra work for you. That's the opposite of what C will do.
Upvotes: 1