周围的堆栈已损坏C

周围的堆栈已损坏C

我正在尝试使用CStrings在C++中执行其他任务,例如从提供的名称中删除所有元音。但是,我似乎无法弄清楚为什么会出现此错误:



为什么会这样呢?

这是代码:

#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>

using namespace std;

    void cStringDemo();
    void stringDemo();
    void removeCVowels(char myGuess[50]);

int main() {
    cStringDemo();
    cin.get();
    cin.ignore();
}


void cStringDemo() {
    char name[] = "Seth Smith";
    char guess[50];
    cout << "Guess my name! [First and Last, EX: Bobby Hall.]" << endl;
    cin.get(guess, 20);
    if (strcmp(name, guess) == 0) {
        cout << "Correct!" << endl;
    }
    else {
    cout << "Incorrect!" << endl;
    }
    cout << "You guessed " << guess << "." << endl;

    removeCVowels(guess);

}

void removeCVowels(char myGuess[50]) {
    char nameNoVowel[50];
    strcpy_s(myGuess, 100, nameNoVowel);
    for (int x = 0; x < 50; x++) {
        if (nameNoVowel[x] == 'a' || nameNoVowel[x] == 'e' || nameNoVowel[x] == 'i' || nameNoVowel[x] == 'o' || nameNoVowel[x] == 'u' || nameNoVowel[x] == 'A' || nameNoVowel[x] == 'E' ||
        nameNoVowel[x] == 'I' || nameNoVowel[x] == 'O' || nameNoVowel[x] == 'U')
    {
        nameNoVowel[x] = ' ';
    }
    }
}

最佳答案

这是未定义的行为:

void removeCVowels(char myGuess[50]) {
    char nameNoVowel[50];
    strcpy_s(myGuess, 100, nameNoVowel);

您正在从未初始化的nameNoVowel复制到myGuess。您应该交换strcpy_s的参数。另外,即使您交换strcpy_s的两个参数,由于nameNoVowel仅为50个字符,限制也太大了。尝试:
void removeCVowels(char myGuess[50]) {
    char nameNoVowel[50];
    strcpy_s(nameNoVowel, sizeof(nameNoVowel)-1, myGuess);

关于c++ - 变量 “name”周围的堆栈已损坏C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55254546/

10-14 08:35