[英]Reserve RAM in C
我需要有關如何編寫一個C程序的想法,該程序保留指定數量的MB RAM直到一個鍵[ex。 在Linux 2.6 32位系統上按下任意鍵。
*
/.eat_ram.out 200
# If free -m is execute at this time, it should report 200 MB more in the used section, than before running the program.
[Any key is pressed]
# Now all the reserved RAM should be released and the program exits.
*
它是程序的核心功能[保留RAM]我不知道怎么做,從命令行獲取參數,打印[按任意鍵]等等對我來說不是問題。
關於如何做到這一點的任何想法?
您想使用malloc()來執行此操作。 根據您的需要,您還需要:
在大多數情況下,malloc()和memset()(或者有效地執行相同操作的calloc())將滿足您的需求。
最后,當然,你想在不再需要時釋放()內存。
你不能只使用malloc()
將ram分配給你的進程嗎? 那將為你保留RAM,然后你就可以自由地做任何你想做的事了。
這是給你的一個例子:
#include <stdlib.h>
int main (int argc, char* argv[]) {
int bytesToAllocate;
char* bytesReserved = NULL;
//assume you have code here that fills bytesToAllocate
bytesReserved = malloc(bytesToAllocate);
if (bytesReserved == NULL) {
//an error occurred while reserving the memory - handle it here
}
//when the program ends:
free(bytesReserved);
return 0;
}
如果您想了解更多信息,請查看手冊頁(linux shell中的man malloc
)。 如果您不在Linux上,請查看在線手冊頁 。
calloc()
就是你想要的。 它將為您的進程保留內存並向其寫入零。 這可確保為您的進程實際分配內存。 如果malloc()
占用了很大一部分內存,那么操作系統可能會為你實際分配內存而懶,只有在寫入時才實際分配(在這種情況下永遠不會發生)。
這是否應該有效。 雖然我能夠保留比我安裝的RAM更多的RAM,但這應該適用於有效值。
#include <stdio.h>
#include <stdlib.h>
enum
{
MULTIPLICATOR = 1024 * 1024 // 1 MB
};
int
main(int argc, char *argv[])
{
void *reserve;
unsigned int amount;
if (argc < 2)
{
fprintf(stderr, "usage: %s <megabytes>\n", argv[0]);
return EXIT_FAILURE;
}
amount = atoi(argv[1]);
printf("About to reserve %ld MB (%ld Bytes) of RAM...\n", amount, amount * MULTIPLICATOR);
reserve = calloc(amount * MULTIPLICATOR, 1);
if (reserve == NULL)
{
fprintf(stderr, "Couldn't allocate memory\n");
return EXIT_FAILURE;
}
printf("Allocated. Press any key to release the memory.\n");
getchar();
free(reserve);
printf("Deallocated reserved memory\n");
return EXIT_SUCCESS;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.