在c++中分配和释放内存
allocate and deallocate memory in c++
我正试图弄清楚为什么这段代码不能正常工作。我想为一个超过250000个单词的词典文件分配内存。内存分配工作正常。但是可用内存不正常。老实说,我不知道为什么。它在解除分配时中断。下面是代码。非常感谢。
#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]) {
请不要忘记添加
#include <iomanip>
带有setd::setw
声明的
相关文章:
- 如何在c++中释放内存
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- std::unordered_map析构函数不释放内存?
- 在C++中释放内存期间,迭代器与指针有何不同
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 释放内存(主题模板)时出现问题
- 使用后自动释放内存
- C++ 如何释放内存
- 从函数内对象的向量中释放内存
- C++ 在不释放内存的情况下调用析构函数
- 多个线程之间的获取-释放内存顺序
- C++ - 析构函数只是释放内存还是实际删除对象
- 使用 RAII 替换最终块以释放内存
- 如何通过带有指向基类的指针的删除运算符释放内存
- 代码中的"sprintf"用法是否需要释放内存?
- C++何时使用 delete[] 并正确释放内存?
- 为什么此获取和释放内存围栏不能给出一致的值?
- 抛出新表达式的参数子表达式时释放内存
- 在这种情况下,如何释放内存?
- 在 c++ 中应按什么顺序释放内存?