不尋找在這一個答案,但一些方向將不勝感激。我所看到的所有地方以及我嘗試過的所有答案都不能解決問題。C++動態內存分配造成損壞的堆
我有指令聲明「動態分配變量到用戶輸入的內容,不能使用placeHolder變量(userInput [256}])來捕獲輸入。
我原來的代碼是:
int main(){
char cont = 'y';
char *userInput = nullptr;
while (cont == 'y' || cont == 'Y')
{
int ptrLength = 0;
userInput = new char[ptrLength];
cout << "Please enter a word or phrase: ";//2. Asks the user to enter any string (any sequence of characters)
while (cin.peek() != '\n'){
cin >> userInput[ptrLength];
ptrLength++;
}
//1. You must use a pointer to a C-string and dynamically allocate just enough memory to store all the characters entered by the user PLUS the ‘\0’ char than must be appended at the end of the C-string.
userInput[ptrLength] = '\0';
cout << endl;
myVowels(userInput, ptrLength);
cout << endl << endl;
//delete [] userInput; //deleting here breaks the program. Not sure why right now.
//userInput = nullptr;
//5. The user must be asked if he/she wants to continue entering values or quit.
cout << endl << "To enter another phrase press Y. To exit press any key." << endl;
cin >> cont;
cin.clear();
cin.ignore(256, '\n');
}//end while cont = Y
delete userInput;
userInput = nullptr;
system("pause");
return 0;
}
更新的代碼:
int main(){
char cont = 'y';
char *userInput = nullptr;
while (cont == 'y' || cont == 'Y')
{
int num = 10;
int ptrLength = num;
userInput = new char[ptrLength];
char *temp = nullptr;
cout << "Please enter a word or phrase: ";//2. Asks the user to enter any string (any sequence of characters)
//FIX I FOUND, BUT IT DOES NOT WORK AT ALL
while (cin.peek() != '\n'){
cin >> userInput[ptrLength];
if (ptrLength = num){
num *= num;
temp = new char[num];
for (int i = 0; i < num/2; i++)
{
temp[i] = userInput[i];
}
delete [] userInput;
userInput = temp;
delete [] temp;
}
}
//1. You must use a pointer to a C-string and dynamically allocate just enough memory to store all the characters entered by the user PLUS the ‘\0’ char than must be appended at the end of the C-string.
userInput[ptrLength] = '\0';
cout << endl;
myVowels(userInput, ptrLength);
cout << endl << endl;
//userInput = nullptr;
//delete [] userInput; //This works, but by switching to nullptr I am not deleting the memory allocated. If I just have the delete with or without [] the program breaks. Tried with user input declared inside and outside of the WHILE statement. Heap is being corrupted.
//5. The user must be asked if he/she wants to continue entering values or quit.
cout << endl << "To enter another phrase press Y. To exit press any key." << endl;
cin >> cont;
cin.clear();
cin.ignore(256, '\n');
}//end while cont = Y
delete userInput;
userInput = nullptr;
system("pause");
return 0;
}
我知道堆被損壞,我從我改變了分配內存的方式懷疑。我不確定爲什麼修復程序無法正常工作,所以這是所有的教程。
'(X^2)/ 2 = x'和'(ptrLength = NUM)=(ptrLength == NUM)'!。並且你釋放你的原始和新的字符緩衝區。也許橡皮鴨會幫助。 –
@JamesRoot'(x^2)!=(x * x)'in C++ – MikeCAT