简体   繁体   English

C ++ strcpy内存泄漏

[英]C++ strcpy memory leak

I have a C++98 test code. 我有一个C ++ 98测试代码。 This code make a horrible memory lake. 这段代码制造了一个可怕的记忆湖。 Why? 为什么? Memory consumption after the release of pointers is the same as before the release. 释放指针之后的内存消耗与释放之前相同。

#include <iostream>
#include "string.h"


using namespace std;

void test();

int main() {
    test();
    cout << "Freed" << endl;
    int input;
    cin >> input;
    cout << "Good bye" << endl;
    return 0;
}

void test() {
    int input;
    int count = 40000000;
    const char *str = "9 770123456789123456123";
    char **pMsg = new char *[count];
    cout << "Register: " << count << endl;
    cin >> input;
    for (int i = 0; i < count; i++) {
        pMsg[i] = new char[strlen(str) + 1];
        strcpy(pMsg[i], str);
    }
    cout << "Full pointers" << endl;
    cin >> input;

    for (int i = 0; i < count; i++) {
        delete[] pMsg[i];
    }
    delete[] pMsg;
}

In principle your memory doesn't leak, because you've a delete[] fore every new[] . 原则上,您的内存不会泄漏,因为每个new[]前都有一个delete[] new[]

But when you allocate huge amounts of memory (and even in general, whenever you allocate memory), you should consider the case the allocation fails: 但是,当您分配大量内存时(甚至通常在任何时候分配内存时),都应考虑分配失败的情况:

    ...
    try {
        test();
    }
    catch(bad_alloc) {
        cerr << "No more memory !" <<endl; 
    }
    ...

The fact that an exception is raised (which happens here), will cause your code to leave test() before the deletes take place. 引发异常(在此处发生)的事实将导致您的代码在删除发生之前离开test() So due to the exception, your memory will leak. 因此,由于异常,您的内存将泄漏。

Remark: The best way to avoid such memory leaks is to use the RAII idiom: you make memory allocation only inside an object, and you free the memory in the object's destructor. 备注: 避免此类内存泄漏的最佳方法是使用RAII惯用语:仅在对象内部进行内存分配,然后释放对象的析构函数中的内存。 As all objects that go out of scope will be deleted, this will make sure that memory freing always takes place, even in case of exceptions. 由于所有超出范围的对象都将被删除,因此即使在发生异常的情况下,也可以确保始终进行内存争夺。

"Memory consumption after the release of pointers is the same as before the release". “释放指针之后的内存消耗与释放之前相同”。 This is not indicative, many implementations of free will not usually return the memory to the OS, instead "recycling" it for future allocations. 这不是指示性的,许多free实现通常不会将内存返回给OS,而是“回收”它以供将来分配。 See this question . 看到这个问题

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

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