简体   繁体   English

删除char指针在析构函数中不起作用

[英]Delete char pointer not working in destructor

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 Program.h

class Program
{
     char* fileName;
public:
     Program();
     ~Program();
     void ReadFile(void);
};

Program.cpp 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; 现在,当我把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? 在析构函数中,它在屏幕上输出“ in destructor”,但fileName不会被删除。如果我使用delete []fileName;并在file.close() fileName被删除后将其放在ReadFile() ,为什么呢?

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. 我只是想摆脱任何内存泄漏,而fileName是我遇到的唯一麻烦,因此我只将代码粘贴到使用fileName的地方。

Any help is appreciated. 任何帮助表示赞赏。

Additional information: I am using Visual Studio to write this and am using the Memory Leak Detection. 附加信息:我正在使用Visual Studio编写此代码,并且正在使用内存泄漏检测。 This is what it outputs: 这是它的输出:

Detected memory leaks! 检测到内存泄漏!
Dumping objects -> 转储对象->
{132} normal block at 0x005D49A0, 40 bytes long. {132} 0x005D49A0的正常块,长40个字节。
Data: 6E 61 6D 65 73 2E 74 78 74 00 CD CD CD CD CD CD 数据:6E 61 6D 65 73 2E 74 78 74 00 CD CD CD CD CD CD CD
Object dump complete. 对象转储完成。
The program '[10772] program1.exe: Native' has exited with code 0 (0x0). 程序“ [10772] program1.exe:本机”已退出,代码为0(0x0)。

which is why I suspect delete []fileName; 这就是为什么我怀疑delete []fileName; didn't work. 没有用

also, this is what the int main() looks like 同样,这就是int main()样子

int main(){
     Program abc;
     abc.ReadFile();
}

Oh, and Program.h can not be changed. 哦,Program.h无法更改。 Only .cpp can be change it's part of my requirements. 只有.cpp可以更改,这是我要求的一部分。

If filename is used only in readFile - then I advise you to remove it from Program class and make it automatic variable in that function: 如果文件名仅在readFile中使用-那么我建议您从Program类中将其删除,并在该函数中使其成为自动变量:

void Program::ReadFile(void){
     char fileName[40];
     ...
     file.close();
     // no delete [] necessary
}

Your problem might be related to 您的问题可能与

  1. Not initializing filename to nullptr in constructor 未在构造函数中将文件名初始化为nullptr
  2. Not defining copy c-tor, assignment operator 未定义复制c-tor,赋值运算符
  3. Your are not deleting old filename in readFile 您没有删除readFile中的旧文件名

So, do not use your member variables as automatic variables to your methods. 因此,请勿将成员变量用作方法的自动变量。

If you have to have this member varible - change it to array - do not allocate it: 如果必须具有该成员变量-将其更改为数组-不要分配它:

class Program {
private:
  // char* filename;
  char filename[40];
}; 

[UPDATE] [UPDATE]

Your .h file is incorrect - it breaks rule of three (see http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming )) - copy constructor and assignment operator is missing. 您的.h文件不正确-违反了三个规则(请参阅http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))-复制构造函数和赋值运算符缺失。 So be aware not to copy your Program class in any way of you cannot change this header. 因此请注意,不要以无法更改此标头的任何方式复制Program类。

After update only one thing is missing in your program: 更新后,程序中仅缺少一件事:

Either add delete[] filename at the beginning of your readFile: 在readFile的开头添加delete[] filename

void Program::ReadFile(void){
     delete [] filename;
     fileName = new char[40];

Or (better) - do not re-allocate every time readFile is called: 或者(更好)-不要在每次调用readFile时重新分配:

void Program::ReadFile(void){
     if (!filename)
         fileName = new char[40];

Or (best) - allocate this memory in constructor only: 或(最佳)-仅在构造函数中分配此内存:

Program::Program() : filename(new char[40]) {}
void Program::ReadFile(void){
   // fileName = new char[40];

Are you sure your main is exactly as posted here? 您确定main内容与此处的内容完全一样吗? If you just define abc globally, it will be freed after memory dump report memory leaks and you may see invalid reports! 如果仅全局定义abc ,它将在内存转储报告内存泄漏后被释放,并且您可能会看到无效的报告! You can insert a break point in the destructor and see if memory leaks reported after or before destructor 您可以在析构函数中插入一个断点,并查看是否在析构函数之后或之前报告了内存泄漏

fileName clearly is getting deleted: the code in the destructor says so. fileName显然已被删除:析构函数中的代码如此表示。 But if the code you didn't show calls ReadFile more than once, the class will leak memory because each call to ReadFile allocates a new memory block and overwrites the pointer to the previous block. 但是,如果您未显示的代码多次调用ReadFile ,则该类将泄漏内存,因为对ReadFile每次调用都会分配一个新的内存块,并覆盖指向前一个块的指针。

Think RAII: Resource Allocation Is Initialization. 思考RAII:资源分配就是初始化。 In the constructor, allocate the memory block. 在构造函数中,分配内存块。 In the destructor, delete it. 在析构函数中,将其删除。 Then ReadFile doesn't have to worry about allocating the block. 然后, ReadFile不必担心分配块。

Or, even better, do as @PiotrNycz says, and change the pointer into an array. 或者,甚至更好,按照@PiotrNycz的说明进行操作,然后将指针更改为数组。 No need for dynamic allocation. 无需动态分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在析构函数中删除指向char *向量的指针(不起作用) - Delete pointer to vector of char* in destructor (Not working) 如何删除析构函数中的void指针? - How to delete the void pointer in destructor? 尝试删除析构函数中已删除的指针 - Trying to delete already-deleted pointer in destructor 无法删除类的析构函数中指向数组的成员指针 - Unable to delete member pointer to array in destructor for class 如何安全地删除析构函数中的线程指针? - How to safely delete a thread pointer in a destructor? "析构函数会删除内置类型和指针对象吗?" - Will destructor delete built-in types and pointer objects? 字符指针分配不起作用 - Char pointer assignment not working 删除一个NULL指针在写入析构函数时不会调用重载删除 - delete a NULL pointer does not call overloaded delete when destructor is written 有没有办法在析构函数中删除一个没有用 new 运算符分配的指针? 如果是这样,我应该在析构函数中删除它吗? - Is there a way to delete a pointer that has not been assigned with new operator in the destructor? If so, should I delete it in the destructor? 我如何在指向Mat析构函数〜Mat()的指针上调用delete - How would I call delete on a pointer to a Mat destructor ~Mat()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM