I have a program where i ask the user for the name of a text file, I open the text file do stuff with it (read, write), then I close the file and exit the program.
Program.h
class Program
{
char* fileName;
public:
Program();
~Program();
void ReadFile(void);
};
Program.cpp
Program::Program(){
//contstructor
fileName=NULL;
}
Program::~Program(){
cout << "in destructor" ;
delete []fileName;
}
void Program::ReadFile(void){
fileName = new char[40];
cout <<"Please enter the name of the file to open: ";
cin.clear();
cin.getline(fileName, 40);
ifstream file (fileName);
if(file.is_open()){
//do stuff
}
file.close();
}
right now when I put delete []fileName; in the destructor it outputs ""in destructor" on the screen but fileName does not get deleted. If I take delete []fileName; and put it in ReadFile() after file.close() fileName gets deleted. Why is that?
The rest of my program works perfectly which is why none of that code is pasted. I am just trying to rid any memory leaks and fileName is the only one I am having trouble with so therefore I only pasted the code where fileName is used.
Any help is appreciated.
Additional information: I am using Visual Studio to write this and am using the Memory Leak Detection. This is what it outputs:
Detected memory leaks!
Dumping objects ->
{132} normal block at 0x005D49A0, 40 bytes long.
Data: 6E 61 6D 65 73 2E 74 78 74 00 CD CD CD CD CD CD
Object dump complete.
The program '[10772] program1.exe: Native' has exited with code 0 (0x0).
which is why I suspect delete []fileName; didn't work.
also, this is what the int main() looks like
int main(){
Program abc;
abc.ReadFile();
}
Oh, and Program.h can not be changed. Only .cpp can be change it's part of my requirements.
fileNameisn't being deleted?<<(void*)fileNameto the logging in the destructor. Either it will report the same address as the leak detector (in which case either the leak detector is broken or else you've corrupted the heap), or else it will report a different address (in which case you've overwrittenfileNamewith a different value somewhere between allocating the memory and the destructor call).