Reputation: 2217
In my CST class we are learning about memory on the heap in C++. Keep in mind this is how the code should be written (must use no std::vector or similar helpful classes). Below is the code I wrote to my assignment and I tested it for memory leaks through Visual Studio and is returns:
{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
which is this line : names[i] = new char[257];
but later on I delete it with : delete [] names[i];
Don't know why this isn't working. Here is my code consisting of a simple recursive function and the 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;
}
Where is the memory leak? Any help is appreciated. Thanks!
Upvotes: 0
Views: 126
Reputation: 198
If this if happens names
variable will leak.
if (!cin.good()) return; //end of file or errors
To be precise in this case new char[257];
will not be deallocated on return.
Upvotes: 1
Reputation: 49
Memory Leak Detection This line will output memory leak information to output window.
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Take the value in the paranthesis and insert into this line below (183, 184, 150). The application will then break at the allocation of the memory leak which you can trace back through the call stack.
_CrtSetBreakAlloc(Your value);
Adding info specifically for this thread:
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.
To delete:
for(int i=0; i<size; i++){ delete array[i]; } //delete the objects.
delete[] array; //delete the array.
Upvotes: 1