mmap,malloc分配随机内存
随机数1G
#cat malloc_rand_1g.c
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand, system */
#include <unistd.h>
#include <memory.h>
int main ()
{
int size;
int n;
char * buffer;
size=1024*1024*1024; //1G
printf ("输入字符串的长度:%d bytes\n",size);
//scanf ("%d", &i);
buffer = (char*)malloc(sizeof(char) * size); // 字符串最后包含 \0
if(buffer==NULL) exit(1); // 判断是否分配成功
memset(buffer,'a',sizeof(char) * size);
printf("total bytes:%d bytes \n",sizeof(char) * size);
// 随机生成字符串
for(n=0; n<size; n++){
buffer[n] = rand()%26+'a';
// printf("%c",buffer[n]);
}
printf("\n");
buffer[size+1]='\0';
// printf ("随机生成的字符串为:%s\n",buffer);
printf("wait about 1800s....\n");
sleep(1800);
free(buffer); // 释放内存空间
printf("clean up....\n");
return 0;
}
memset(a)
#cat malloc_a_1g.c
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand, system */
#include <unistd.h>
#include <memory.h>
int main ()
{
int size;
int n;
char * buffer;
size=1024*1024*1024; //1G
printf ("输入字符串的长度:%d bytes\n",size);
//scanf ("%d", &i);
buffer = (char*)malloc(sizeof(char) * size); // 字符串最后包含 \0
if(buffer==NULL) exit(1); // 判断是否分配成功
memset(buffer,'a',sizeof(char) * size);
printf("total bytes:%d bytes \n",sizeof(char) * size);
// 随机生成字符串
for(n=0; n<size; n++){
buffer[n] = 'a';
// printf("%c",buffer[n]);
}
printf("\n");
buffer[size+1]='\0';
// printf ("随机生成的字符串为:%s\n",buffer);
printf("wait about 1800s....\n");
sleep(1800);
free(buffer); // 释放内存空间
printf("clean up....\n");
return 0;
}
mmap
#cat mmap_1g.c
#include<stdio.h>
#include<sys/mman.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 1024*1024*1024
#define GB 1
int main(int argc,char* argv[]) {
char *p;
int i=1;
for (i=1;i<=GB;i++) {
if ((p = (char *)mmap(NULL,SIZE, PROT_READ |
PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)) == (void *)-1) {
perror("mmap");
}
memset(p,'c',SIZE);
printf("Get %d GB...\n",i);
}
sleep(3000);
return 0;
}
muahao@aliyun.com