gpt4 book ai didi

c++ - 使用静态链接替换 ​​Windows tcmalloc

转载 作者:可可西里 更新时间:2023-11-01 10:29:39 35 4
gpt4 key购买 nike

一个C++项目遇到内存碎片问题,尝试如下:

  1. nedmalloc-没有通过压力测试(15 小时后崩溃),这意味着它在大多数情况下都有效,但不是全部。以及比其他分配器更多的内存使用量。

  2. jemalloc-还没有为 Windows 做好准备?

  3. tcmalloc-使用带有静态链接的主机代码编译,但与 CRT 符号冲突。我可以只使用像 tc_malloc(...) 这样的别名来构建我自己的分配包装器吗?怎么做?

有什么意见吗?提前致谢。

最佳答案

使用 this API 设置您的项目以使用 Windows 低碎片堆 (LFH)在程序的开始。这可能会解决您的问题,而无需对自定义实现进行更多工作。

示例代码,直接取自 MSDN:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

#define HEAP_LFH 2

int __cdecl _tmain()
{
BOOL bResult;
HANDLE hHeap;
ULONG HeapInformation;

//
// Note: The HeapSetInformation function is available on Windows 2000 with SP4
// only if hotfix KB 816542 is installed. To run this example on Windows 2000,
// use GetProcAddress to get a pointer to the function if available.
//

//
// Enable heap terminate-on-corruption.
// A correct application can continue to run even if this call fails,
// so it is safe to ignore the return value and call the function as follows:
// (void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
// If the application requires heap terminate-on-corruption to be enabled,
// check the return value and exit on failure as shown in this example.
//
bResult = HeapSetInformation(NULL,
HeapEnableTerminationOnCorruption,
NULL,
0);

if (bResult != FALSE) {
_tprintf(TEXT("Heap terminate-on-corruption has been enabled.\n"));
}
else {
_tprintf(TEXT("Failed to enable heap terminate-on-corruption with LastError %d.\n"),
GetLastError());
return 1;
}

//
// Create a new heap with default parameters.
//
hHeap = HeapCreate(0, 0, 0);
if (hHeap == NULL) {
_tprintf(TEXT("Failed to create a new heap with LastError %d.\n"),
GetLastError());
return 1;
}

//
// Enable the low-fragmenation heap (LFH). Starting with Windows Vista,
// the LFH is enabled by default but this call does not cause an error.
//
HeapInformation = HEAP_LFH;
bResult = HeapSetInformation(hHeap,
HeapCompatibilityInformation,
&HeapInformation,
sizeof(HeapInformation));
if (bResult != FALSE) {
_tprintf(TEXT("The low-fragmentation heap has been enabled.\n"));
}
else {
_tprintf(TEXT("Failed to enable the low-fragmentation heap with LastError %d.\n"),
GetLastError());
return 1;
}

return 0;
}

关于c++ - 使用静态链接替换 ​​Windows tcmalloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3811298/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com