简体   繁体   中英

C++ strcpy memory leak

I have a C++98 test code. 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[] .

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. 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. 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. See this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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