在我的CST类中,我们正在学习C ++中的堆内存。请记住,这是代码应该如何编写(必须使用没有std :: vector或类似的有用类)。下面是我写给我的作业的代码,我通过Visual Studio测试它是否有内存泄漏,并返回:
{173} normal block at 0x008BF658, 257 bytes long.
Data: < > 00 CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
这一行:names[i] = new char[257];
但稍后我会将其删除:delete [] names[i];
不知道为什么这不起作用。这是我的代码,包含一个简单的递归函数和main:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include "CST126SRS02.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
void reverseNames(int &numNames, char ** &names, char ** &temp)
{
//get names from user, put names in ragged array
names = new char * [numNames] {};
int i = 0;
while (i < numNames) {
//add name to ragged array
if (cin.peek() == '\n' && i != 0) break; //make sure there are names
if (!cin.good()) return; //end of file or errors
names[i] = new char[257];
cin >> setw(256) >> names[i];
i++;
if (i == numNames) {
//need a bigger array, reallocation
numNames *= 2;
temp = new char *[numNames] {};
for (int j = 0; j < numNames / 2; j++)
{
temp[j] = names[j];
}
delete[] names;
names = temp;
}
}
//output names in reverse order
for (int i = numNames - 1; i >= 0; i--) {
if (names[i] != nullptr) cout << names[i] << " ";
delete [] names[i]; //also deletes temp items!
}
delete [] names; //also deletes temp array!
cout << endl;
//recursion
numNames = 1;
reverseNames(numNames, names, temp);
}
int main()
{
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
//_CrtSetBreakAlloc(173);
int numNames = 1;
char **names;
char ** temp;
//recursive function, runs until user ends file
reverseNames(numNames, names, temp);
delete [] names;
_CrtDumpMemoryLeaks();
return 0;
}
内存泄漏在哪里?任何帮助表示赞赏。谢谢!
答案 0 :(得分:1)
内存泄漏检测 该行将内存泄漏信息输出到输出窗口。
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
获取paranthesis中的值并插入下面的这一行(183,184,150)。 然后应用程序将在内存分配时中断 泄漏,您可以通过调用堆栈追溯。
_CrtSetBreakAlloc(Your value);
专门为此线程添加信息:
char** array = new char*[size]; //This is an array of pointers.
for(int i=0; i<size;i++) { array[i] = new char(); } // Each element in the array creates an object.
要删除:
for(int i=0; i<size; i++){ delete array[i]; } //delete the objects.
delete[] array; //delete the array.
答案 1 :(得分:1)
如果发生这种情况,names
变量将泄漏。
if (!cin.good()) return; //end of file or errors
准确地说,在这种情况下,new char[257];
将不会在返回时被解除分配。