Reputation: 13
I'm trying to use CStrings to do miscellaneous tasks in C++, such as remove all the vowels from the name provided. However, I can't seem to figure out why I'm getting this error:
Stack around the variable "name" was corrupted.
Why is this happening?
Here is the code:
#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] = ' ';
}
}
}
Upvotes: 1
Views: 872
Reputation: 1344
There are a few problems in the code that you posted. Below is code fixed with explanation in comments of what was wrong:
void cStringDemo() {
char name[] = "Seth Smith";
char guess[50] = {0}; //in here initialize the table with zeros
cout << "Guess my name! [First and Last, EX: Bobby Hall.]" << endl;
cin.get(guess, 20); // I am not sure why you want 20 characters and have array of size 50
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] = {0}; //it is always good to initialize variables
strcpy_s(myGuess, 50, nameNoVowel); //here lies the problem you tried to copy 100
// characters from array size of 50 this leads
//to undefined behaviour of your program and stack corruption
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] = ' ';
}
}
}
Upvotes: 1
Reputation: 8475
This is undefined behavior:
void removeCVowels(char myGuess[50]) {
char nameNoVowel[50];
strcpy_s(myGuess, 100, nameNoVowel);
You are copying from uninitialized nameNoVowel
to myGuess
. You should swap the arguments of strcpy_s
. Also, even if you swap the two arguments of strcpy_s
, the limit of 100 is also too big, since nameNoVowel is only 50 chars. Try:
void removeCVowels(char myGuess[50]) {
char nameNoVowel[50];
strcpy_s(nameNoVowel, sizeof(nameNoVowel)-1, myGuess);
Upvotes: 1