首页 > 解决方案 > 为什么“unordered_map”分配内存2次?

问题描述

#include <iostream>
#include <unordered_map>

#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl

void* operator new(size_t size) {
    println("Allocated: " << size << " Bytes of memory");
    return malloc(size);
}

void operator delete(void* object) {
    println("Deleted !");
    free(object);
}

template<typename T>
T input(const char* string) {
    print(string);
    T temp;
    std::cin >> temp;
    return temp;
}

int main() {
    //println(sizeof(const char*) * 4 + sizeof(int) * 4);
    std::unordered_map<const char*, int> ages;
    ages.reserve(3);
    ages["Ahmed"] = 17;
    std::initializer_list<const char*> names = {"Asem", "Khalid"};
    int i = 17;
    for (const char* name : names) {
        ages[name] = i;
        i++;
    }
    for (auto age : ages) {
        println(age.first << " is " << age.second << " years old!");
    }
}

当我尝试“以发布模式”运行此代码时,它给了我这个输出:

Allocated: 16 Bytes of memory
Allocated: 64 Bytes of memory
Allocated: 16 Bytes of memory
Allocated: 16 Bytes of memory
Allocated: 16 Bytes of memory
Khalid is 18 years old!
Asem is 17 years old!
Ahmed is 17 years old!
Deleted !
Deleted !
Deleted !
Deleted !
Deleted !

我尝试调试代码,我注意到当这一行:

std::unordered_map<const char*, int> ages;

被执行它为时间分配内存,输出:

Allocated: 16 Bytes of memory
Allocated: 64 Bytes of memory

为什么会发生这种情况?!,顺便说一句,当我尝试在调试模式下运行它时,它给了我超过 2 个分配:/ 编辑:我的平台是 Windows 10 pro x64,我正在使用 msvc

标签: c++visual-c++heap-memoryallocationunordered-map

解决方案


您可以使用 dbghelp 库在内存分配上打印内部堆栈跟踪。这将使您深入了解 unordered_map 分配内存的 stl。


#pragma comment(lib, "Dbghelp.lib")

using namespace std;


#define TRACE_MAX_STACK_FRAMES 1024
#define TRACE_MAX_FUNCTION_NAME_LENGTH 1024


int printStackTrace()
{
    void *stack[TRACE_MAX_STACK_FRAMES];
    HANDLE process = GetCurrentProcess();
    SymInitialize(process, NULL, TRUE);
    WORD numberOfFrames = CaptureStackBackTrace(0, TRACE_MAX_STACK_FRAMES, stack, NULL);
    SYMBOL_INFO *symbol = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO) + (TRACE_MAX_FUNCTION_NAME_LENGTH - 1) * sizeof(TCHAR));
    symbol->MaxNameLen = TRACE_MAX_FUNCTION_NAME_LENGTH;
    symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
    DWORD displacement;
    IMAGEHLP_LINE64 *line = (IMAGEHLP_LINE64 *)malloc(sizeof(IMAGEHLP_LINE64));
    line->SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    for (int i = 0; i < numberOfFrames; i++)
    {
        DWORD64 address = (DWORD64)(stack[i]);
        SymFromAddr(process, address, NULL, symbol);
        if (SymGetLineFromAddr64(process, address, &displacement, line))
        {
            printf("\tat %s in %s: line: %lu: address: 0x%0X\n", symbol->Name, line->FileName, line->LineNumber, symbol->Address);
        }
        else
        {
            printf("\tSymGetLineFromAddr64 returned error code %lu.\n", GetLastError());
            printf("\tat %s, address 0x%0X.\n", symbol->Name, symbol->Address);
        }
    }
    return 0;
} 

void* operator new(size_t size) {
    println("Allocated: " << size << " Bytes of memory");
    printStackTrace(); // add this
    return malloc(size);
}```

推荐阅读