gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:01:58 25 4
gpt4 key购买 nike

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

如果我这样做:

MyClass::MyClass(char* myString){

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

}

然后一切都很好。但是,如果我这样做:

MyClass::MyFunction(){

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

}

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

问候

最佳答案

您需要的答案...

是使用C++:

std::string anotherString = "fred";
anotherString += "bob";

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

是 Let_Me_Be 和 Moo-Juice 所说的组合。

这段代码:

char* anotherString = "fred";

是极其危险的,应该无论如何避免。 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");

当然,在现实世界中,您可能事先不知道字符串的大小,因此您会使用 malloc 来分配足够的缓冲区。

关于c++ - 使用strcat时访问冲突写入位置错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4098182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com