使用strcat时访问冲突写入位置错误

paj*_*777 0 c c++

我在C++中使用strcat函数时遇到问题.

如果我做 :

MyClass::MyClass(char* myString){

char* AnotherString = myString;
strcat(AnotherString, "bob");

}
Run Code Online (Sandbox Code Playgroud)

一切都很好.但是,如果我这样做:

MyClass::MyFunction(){

char* AnotherString = "fred";
strcat(AnotherString, "bob");

}
Run Code Online (Sandbox Code Playgroud)

我在strcat.asm中得到一个未处理的异常.有任何想法吗?

问候

Ped*_*ino 10

你需要的答案......

是使用C++:

std::string anotherString = "fred";
anotherString += "bob";
Run Code Online (Sandbox Code Playgroud)

你可能想要的答案......

这就是Let_Me_Be和Moo-Juice所说的结合.

这段代码:

char* anotherString = "fred";
Run Code Online (Sandbox Code Playgroud)

是非常危险的,应该尽一切可能避免.fred存储在存储器的只读部分中,不能更改 - 它基本上与const char*所有实际用途相同.请注意,char anotherString[] = "fred";是一个完全不同的故事,因为它实际上是存储复制fred,它可以随意修改.

但是,正如Moo-Juice指出的那样,strcat将第二个参数连接在第一个参数之后,这意味着第一个字符串必须有足够的分配空间来容纳它们.所以在你的情况下,char anotherString[] = "fred";你没有好处,因为anotherString只有5个字节长.你应该写:

char anotherString[8] = "fred"; // fred + bob + 1
strcat(anotherString, "bob");
Run Code Online (Sandbox Code Playgroud)

当然,在现实世界的场景中,您可能不会提前知道字符串大小,因此您将使用malloc分配一个充足的缓冲区.

  • @David Thornley:我故意推荐`malloc()`.如果你有'new`,你就是C++; 如果您使用的是C++,请使用`std :: string`! (4认同)

Moo*_*ice 7

"dest"指向的缓冲区strcat(dest, src)必须足够大以容纳结果字符串.所以:

char* anotherString = "fred"; // 5 bytes including zero-terminator
Run Code Online (Sandbox Code Playgroud)

例如,没有"鲍勃"的空间.

但是,你已经用C++发布了这个,那你为什么要使用strcat()呢?

#include <string>

std::string another = "fred";
another.append("bob");
Run Code Online (Sandbox Code Playgroud)

  • @Let_Me_Be或者,你可以是建设性的并指出错误,而不是好战. (5认同)
  • "fred"字符串也作为程序代码的一部分存储在只读存储器中.所以即使你这样做:strcpy(anotherString,"bob"); 你会得到一个访问语音错误. (4认同)
  • @Let_Me_Be:也许你应该更关心更新你的答案而不是生气的Moo-Juice得到提升.第一句"首先,编译器不应该允许你编译这个`是不正确的; 编译成功,尽管有警告(在GCC上).即使在Level4警告设置下,VS2010也不会生成警告. (2认同)