在C++中分配和释放内存
问题描述:
我想弄清楚为什么这段代码不能正常工作。我想为超过250,000字的字典文件分配内存。内存分配工作正常。但是空闲的内存不会。而且,老实说,我不知道为什么。它在释放期间中断。以下是代码。 谢谢。在C++中分配和释放内存
#include <iostream> // For general IO
#include <fstream> // For file input and output
#include <cassert> // For the assert statement
using namespace std;
const int NumberOfWords = 500000; // Number of dictionary words
//if i change to == to exact number of words also doesnt work
const int WordLength = 17; // Max word size + 1 for null
void allocateArray(char ** & matrix){
matrix = new char*[NumberOfWords];
for (int i = 0; i < NumberOfWords; i++) {
matrix[i] = new char[WordLength];
// just to be safe, initialize C-string to all null characters
for (int j = 0; j < WordLength; j++) {
matrix[i][j] = NULL;
}//end for (int j=0...
}//end for (int i...
}//end allocateArray()
void deallocateArray(char ** & matrix){
// Deallocate dynamically allocated space for the array
for (int i = 0; i < NumberOfWords; i++) {
delete[] matrix[i];
}
delete[] matrix; // delete the array at the outermost level
}
int main(){
char ** dictionary;
// allocate memory
allocateArray(dictionary);
// Now read the words from the dictionary
ifstream inStream; // declare an input stream for my use
int wordRow = 0; // Row for the current word
inStream.open("dictionary.txt");
assert(!inStream.fail()); // make sure file open was OK
// Keep repeating while input from the file yields a word
while (inStream >> dictionary[wordRow]) {
wordRow++;
}
cout << wordRow << " words were read in." << endl;
cout << "Enter an array index number from which to display a word: ";
long index;
cin >> index;
// Display the word at that memory address
cout << dictionary[index] << endl;
deallocateArray(dictionary);
return 0;
}
答
的问题是在下面的行:
while (inStream >> dictionary[wordRow]) {
上有输入线长度没有限制并且应用覆盖字符串缓冲区中的至少一个。我想解决这个问题是这样的:
while (inStream >> std::setw(WordLength - 1) >> dictionary[wordRow]) {
请不要忘记与setd::setw
声明
什么 '游' 的意思是添加
?它崩溃,或不编译,它提供了哪个错误信息? –
另外,考虑用memset代替'for(int j = 0; j
@DenisSheremet停止并且VS中的cmd窗口不会关闭。 – Art