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;
}

转载于:https://www.cnblogs.com/muahao/p/7489254.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值