[英]Access violation writing location error when using strcat
在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
分配足夠的緩沖區。
strcat(dest, src)
“ dest”所指向的緩沖區必須足夠大以容納結果字符串。 所以:
char* anotherString = "fred"; // 5 bytes including zero-terminator
例如,沒有空間容納“鮑勃”。
但是,您已經在C ++中發布了此內容,所以為什么仍要使用strcat()?
#include <string>
std::string another = "fred";
another.append("bob");
首先,編譯器不應允許您對此進行編譯(無警告):
char* str = "fred";
正確的代碼是:
const char* str = "fred";
字符串文字是常量,因此您不能修改其內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.