简体   繁体   中英

Memory Leak (char[])

When I run my program, it can run for a while, then all of the sudden, it experiences a huge memory leak. I traced it out using a snapshot of the heap when it crashed, and I have a mysterious char[] with the size of 232,023,801 Bytes. The minutes preceding crash have no unusual behavior until then. The only places where I use char arrays is in the following piece of code:

string ReadString(DWORD64 addr) {

    char* buffer = new char[128];

    bool validChar = true;
    for (int c = 0; c < 128 && validChar; c++) {
        buffer[c] = Mem.Read<char>(addr+ (0x1 * c), sizeof(char));
        if (!isalnum(buffer[c]) && !ispunct(buffer[c]))
            validChar = false;
    }
    string ret= string(buffer);
    delete[] buffer;
    return ret;
}

All this code should be doing is reading a few characters from memory, saving the char array to a string, cleaning up the array, and returning the string. How is the memory leak originating from here? Or does the char[] in the heap snapshot potentially point to another issue?

Assuming that string here is std::string :

You call string(buffer) which assumes that buffer is 0-terminated and allocates a new string. But your code doesn't ensure that buffer is actually 0-terminated, so this can cause undefined behavior, including potentially crashing or allocating too much memory for the string.

You probably want to use the string(buffer, size) constructor instead, which doesn't require buffer to be 0-terminated.

I'd also recommend avoiding the manual new / delete . One way to do this is to create an empty string and push_back the characters you read to it. This avoid the need for buffer .

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