簡體   English   中英

為什么圍繞char數組的堆棧已損壞

[英]Why was the stack around char array was corrupted

我對C ++很陌生,來自Java。 我正在嘗試僅從Char數組中提取第一個單詞,因此我認為創建一個新數組來容納所有第一個單詞chars並將它們傳輸直到循環運行到句子中的空格中是可行的。 這是代碼:

void execute(){
//start with getting the first word
char first_word[20];
int i = 0;
while (input[i] != ' '){ // input is a char array declared and modified with cin, obtaining the command.
    first_word[i] = input[i];
    i++;
}
print(first_word + ' ' + 'h' + ' ' + 'h' + 'a');
}

嘗試執行此操作時,出現錯誤“變量'first_word'周圍的堆棧已損壞”。 為什么會這樣呢?

input是字符數組時, cin >> input不會執行您認為的操作。 >>運算符無法讀入字符數組,而必須使用cin.getline()cin.read() 因此,實際上是通過處理無效的內存導致未定義的行為。

即使它確實起作用,您也不會進行任何邊界檢查。 如果input在遇到空格字符之前有20個以上的字符(或更糟糕的是,根本不包含空格字符),則將first_word的末尾寫入周圍的內存中。

如果您真的想用C ++編寫代碼,請不要在字符串中使用字符數組。 這就是C處理字符串的方式。 C ++改用std::string ,它具有find()substr()方法,還有許多其他方法。 而且std::cin知道如何使用std::string進行操作。

例如:

#include <string>

void execute()
{
    //start with getting the first word
    std::string first_word;
    std::string::size_type i = input.find(' '); // input is a std::string read with cin, obtaining the command.
    if (i != std::string::npos)
        first_word = input.substr(0, i);
    else
        first_word = input;
    std::cout << first_word << " h ha";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM