问题
Can some one tell me what's wrong with this code???
char sms[] = "gr8";
strcat (sms, " & :)");
回答1:
sms
is an array of size 4
1. And you're appending more char literals, which is going outside of the array, as the array can accommodate at max 4
chars which is already occupied by g, r, 8, \0
.
1. By the way, why exactly 4? Answer : Because that there is a null character at the end!
If you mention the size of array as shown below, then your code is valid and well-defined.
char sms[10] = "gr8"; //ensure that size of the array is 10
//so it can be appended few chars later.
strcat (sms, " & :)");
But then C++ provides you better solution: use std::string
as:
#include <string> //must
std::string sms = "gr8";
sms += " & :)"; //string concatenation - easy and cute!
回答2:
Yes, there is no room for the extra characters. sms[]
only allocates enough space to store the string that it is initialized with.
Using C++, a much better solution is:
std::string sms = "gr8";
sms += " & :)";
回答3:
You're copying data into unallocated memory.
When you do this: char sms[] = "gr8";
you create a char array with 4 characters, "gr8" plus the 0 character at the end of the string.
Then you try to copy extra characters to the array with the strcat
call, beyond the end of the array. This leads to undefined behaviour, which means something unpredictable will happen (the program might crash, or you might see weird output).
To fix this, make sure that the array that you are copying the characters to is large enough to contain all the characters, and don't forget the 0 character at the end.
回答4:
In C, arrays don't automatically grow.
sms
has a specific length (4, in this case - three letters and the terminating NULL). When you call strcat
, you are trying to append characters to that array past its length.
This is undefined behavior, and will break your program.
If instead you had allocated an array with a large enough size to contain both strings, you would be okay:
char sms[9] = "gr8";
strcat (sms, " & :)");
C++ has the (basically) the same restrictions on arrays that C does. However, it provides higher level facilities that make it so you don't have to deal with arrays a lot of the time, such as std::string
:
#include <string>
// ...
std::string sms = "gr8";
sms += " & :)";
The reason this is nicer is that you don't have to know ahead of time exactly how long your string will be. C++ will grow the underlying storage in memory for you.
回答5:
Buffer overflow for character array followed by crash somewhere!
回答6:
Your sms buffer is only 4 characters long. strcat will copy 5 more characters over the end of it and corrupt the stack.
来源:https://stackoverflow.com/questions/5947805/appending-character-arrays-using-strcat-does-not-work