Appending character arrays using strcat does not w

2019-07-16 08:31发布

Can some one tell me what's wrong with this code???

char sms[] = "gr8";  
strcat (sms, " & :)");

6条回答
闹够了就滚
2楼-- · 2019-07-16 08:46

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.

查看更多
叼着烟拽天下
3楼-- · 2019-07-16 08:58

Your sms buffer is only 4 characters long. strcat will copy 5 more characters over the end of it and corrupt the stack.

查看更多
我只想做你的唯一
4楼-- · 2019-07-16 09:01

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 += " & :)";
查看更多
劳资没心,怎么记你
5楼-- · 2019-07-16 09:03

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!
查看更多
手持菜刀,她持情操
6楼-- · 2019-07-16 09:06

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.

查看更多
We Are One
7楼-- · 2019-07-16 09:07

Buffer overflow for character array followed by crash somewhere!

查看更多
登录 后发表回答