gpt4 book ai didi

c - 正确释放分配的虚拟内存

转载 作者:行者123 更新时间:2023-11-30 20:24:46 26 4
gpt4 key购买 nike

我一直想知道 CPU 需要多少时间来处理大量 NOP 操作并以某种方式计算每秒的总操作数,所以我想出了以下代码:

#include <string.h>
#include <stdio.h>
#include <time.h>
#include <Windows.h>

int main(){
printf("NOP watch\n");
LPCH buffer=0;
int count=0;
while (true){
int success=0;
do {
printf("NOP count: ");
int success=scanf("%d", &count);
} while (success);
buffer = (LPCH)VirtualAlloc(0, count + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if (!buffer){
printf("Not enough RAM available, code: %d!\n",GetLastError());
}
else {
for (int i = 0; i < count; i++)
buffer[i] = '\x90';
buffer[count] = 0xC3;
clock_t start = clock();
((void(*)())buffer)();
float t = (clock() - start) / (CLOCKS_PER_SEC * 1.0f);
printf(" Time: %f, operations per second: %.3f M\n", t, (count / t) / 1e6);
VirtualFree(buffer, count + 1, MEM_RELEASE);
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
printf(" Available virtual memory: %.2f/%.2f MB\n", statex.ullAvailVirtual / (1024.0f*1024.0f), statex.ullTotalVirtual / (1024.0f * 1024.0f));
}
}
}

我只是分配 count + 1 字节内存,在那里写入 count NOP 并 RET,调用内存块,然后释放内存。但不知何故,VirtualFree(buffer, count + 1, MEM_RELEASE) 并没有释放任何东西,而且我很快就耗尽了内存。哪里错了?

这是示例输出:

NOP count: 500000000
Time: 0.086000, operations per second: 5813.954 M
Available virtual memory: 1558.46/2047.88 MB
NOP count: 500000000
Time: 0.094000, operations per second: 5319.149 M
Available virtual memory: 1081.62/2047.88 MB
NOP count: 500000000
Time: 0.105000, operations per second: 4761.905 M
Available virtual memory: 604.78/2047.88 MB
NOP count: 500000000
Not enough RAM available, code: 8!

最佳答案

我不确定细节,但文档 https://msdn.microsoft.com/en-us/library/windows/desktop/aa366892%28v=vs.85%29.aspx指出如果第三个参数是 MEM_RELEASE,则 VirtualFree 的第二个参数应为零。

关于c - 正确释放分配的虚拟内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32681576/

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