有没有办法编写一个不断使用越来越多内存的程序?我想为此编写一个简单的 C 程序
Is there a way to write a program which keeps using more and more memory? I want to write a simple C program for that
我使用了以下代码,但 top 命令中的 VIRT 列显示已分配常量内存。
#include <stdio.h>
int main (int argc, char *argv[])
{
while(1)
{
int *pointer;
pointer = malloc(10 * sizeof(int));
*(pointer+3) = 99;
}
}
您需要初始化内存。
使用memset
初始化内存:
memset(pointer, 0, the_size);
您也可以使用 calloc
,它不仅可以分配内存,还可以为您填充零:
pointer = calloc(10, sizeof(int));
about calloc:
C 库函数 void *calloc(size_t nitems, size_t size) 分配请求的内存和 returns 指向它的指针。 malloc 和 calloc 的区别在于 malloc 不会将内存设置为零,而 calloc 会将分配的内存设置为零。
我使用了以下代码,但 top 命令中的 VIRT 列显示已分配常量内存。
#include <stdio.h>
int main (int argc, char *argv[])
{
while(1)
{
int *pointer;
pointer = malloc(10 * sizeof(int));
*(pointer+3) = 99;
}
}
您需要初始化内存。
使用memset
初始化内存:
memset(pointer, 0, the_size);
您也可以使用 calloc
,它不仅可以分配内存,还可以为您填充零:
pointer = calloc(10, sizeof(int));
about calloc: C 库函数 void *calloc(size_t nitems, size_t size) 分配请求的内存和 returns 指向它的指针。 malloc 和 calloc 的区别在于 malloc 不会将内存设置为零,而 calloc 会将分配的内存设置为零。