【发布时间】:2019-12-05 07:39:39
【问题描述】:
我目前正在尝试编写一个应该分配最大可用内存的程序。我找到了一个解决方案,它限制了潜在可用内存的区域,直到两个边界相等(见清单)
void enforceMemoryLeakage(void** arrayOfAllocMemory)
{
unsigned int maxMemory = 0x80000000;
unsigned int minMemory = 0x50000000;
unsigned int attempAllocatedMemory = minMemory + (maxMemory - minMemory) / 2;
void* pAllocMemory;
while((maxMemory - minMemory) > 1)
{
pAllocMemory = malloc(attempAllocatedMemory);
if (pAllocMemory != NULL)
{
minMemory = attempAllocatedMemory;
attempAllocatedMemory += (maxMemory - minMemory) / 2;
free(pAllocMemory);
}
else
{
maxMemory = attempAllocatedMemory;
attempAllocatedMemory = minMemory + (maxMemory - minMemory) / 2;
}
}
arrayOfAllocMemory[0] = malloc(maxMemory);
void* pAllocAdditionalMemory = malloc(100);
if (pAllocAdditionalMemory == NULL)
std::cout << "Maximum memory: " << minMemory << "\n";
}
上面显示的代码工作正常。但是如果执行了命令
void* pAllocAdditionalMemory = malloc(100);
if (pAllocAdditionalMemory == NULL)
std::cout << "Maximum memory: " << minMemory << "\n";
我原以为没有更多可用内存了。但是它不起作用,这让我想到了为什么上面显示的方法不起作用的实际问题。
最好的问候
老鼠
【问题讨论】:
标签: algorithm memory memory-leaks malloc