简体   繁体   English

如果我忘记在C ++中释放内存会怎样?

[英]What happens if I forget to deallocate memory in C++

I have a question regarding the memory management in C++. 我对C ++中的内存管理有疑问。 As far as I know, there is no need to deallocate memory in Java, since unused objects will be removed by the JVM garbage collector at some time. 据我所知,不需要用Java释放内存,因为JVM垃圾收集器有时会删除未使用的对象。 My point is, if I forgot to free memory in C++, the used memory addresses will be occupied until I restart the machine and the data in the memory get lost? 我的观点是,如果我忘记了释放C ++中的内存,那么在我重新启动计算机之前,已使用的内存地址将被占用,并且内存中的数据会丢失吗? For example, on the code below I have a simple linked list and you can observe that I do not free memory(which is commented in the destructor): 例如,在下面的代码中,我有一个简单的链接列表,您可以观察到我没有释放内存(在析构函数中进行了注释):

#include <iostream>
using namespace std;

typedef struct Node{
Node* next;
int id;
} *ListPtr;
class LinkedList{
public:`ListPtr header;

LinkedList(){
    header = NULL;
}
~LinkedList(){
    /*
     ListPtr a = header,b;
    while(a != NULL)
    {
        b = a;
        a = a -> next;
        delete b;
    }
    delete a,b;
    cout << "Memory freed!"<< endl;
    */
}

public: void Insert(){
    ListPtr new_element = new Node;
    new_element -> next = NULL;

    if(header == NULL){
        header = new_element;
        header -> id = 0;
    }
    else{
        new_element -> next = header;
        new_element -> id = header -> id + 1;
        header = new_element;
    }
}

public: void Print(){
    ListPtr curr = header;
    while(curr != NULL){
             cout << "[" << &curr -> id << "]" << "-->";
        curr = curr -> next;
    }
    cout << "[NULL]"<<endl;
}};

int main(){
LinkedList list;
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Insert();
list.Print();
return 0;
}

Does it mean that those memory addresses will be occupied until I turn the machine off? 这是否意味着这些内存地址将一直被占用,直到我关闭机器电源? What happens with variables such as integers after the execution of a program is done? 执行完程序后,诸如整数之类的变量会发生什么? Can I free them? 我可以释放他们吗?

The Output for the program is: [0x8622ac]-->[0x86229c]-->[0x86228c]-->[0x86227c]-->[0x8615bc]-->[NULL] 程序的输出为: [0x8622ac]-> [0x86229c]-> [0x86228c]-> [0x86227c]-> [0x8615bc]-> [NULL]

It depends on the operating system. 这取决于操作系统。 Most modern operating systems keeps track of allocated memory per process, so when the process exits all memory allocated by the process should be released. 大多数现代操作系统都会跟踪每个进程分配的内存,因此当进程退出时,应该释放该进程分配的所有内存。

However, not releasing resources after you're done with them will lead to leaks , in the case of memory you will have memory leaks . 但是,用完资源后不释放资源会导致泄漏 ,如果是内存,则会发生内存泄漏 And for long-running processes, those leaks can accumulate, until all resources are used up. 对于长时间运行的流程,这些泄漏可能会累积,直到所有资源用完为止。


Even when the memory and other resources are released automatically on process termination, it's often still considered good style to explicitly release allocated resources before exiting the process. 即使在进程终止时自动释放内存和其他资源,通常仍认为在退出进程之前显式释放分配的资源是一种好方法。

C++ does not have garbage collector like Java and it is programmers duty to free dynamically allocated memory. C ++没有像Java这样的垃圾收集器,程序员有责任释放动态分配的内存。 Operating system clears the memory that was allocated for a application when the application is terminated but there are specific cases where deallocation must be performed by the programmer otherwise it will cause memory leak. 终止应用程序时,操作系统会清除为该应用程序分配的内存,但是在某些特定情况下,程序员必须执行重新分配,否则将导致内存泄漏。

#include <iostream>
using namespace std;
class test {
    public:
    int cl;
};

int main()
{
  test *p;
  p=new(test);
  p->cl=5;
  return 0;
}

When the above program terminates it will free the pointer p but will not free the integer pointed by p though that integer is no longer accessible. 当上述程序终止时,它将释放指针p,但不会释放p指向的整数,尽管该整数不再可访问。

Unless you are using some kind of stripped down real-time operating system, it is extremely unlikely that the system cannot recover all the memory when the process exits. 除非您使用某种简化的实时操作系统,否则当进程退出时,系统极不可能无法恢复所有内存。

That said, it is a good practice to not count on that behavior. 就是说,不要指望这种行为是一种好习惯。 For example, you could include counts of allocated objects in your constructors/destructors. 例如,您可以在构造函数/析构函数中包括分配的对象数。 If they all go to zero before the program exits, you have a good check against memory leaks. 如果它们在程序退出前都归零,则可以很好地检查内存泄漏。 If those counts are non-zero, you have a memory leak somewhere. 如果这些计数不为零,则您在某处存在内存泄漏。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM