可以用来编译出吃内存进程的代码段

下面的代码是根据网上的某一篇博客整理得出的,在实践中使用过的“用来编译出吃内存进程的代码段”。原博客主可以联系我加上原始链接

实际使用时,会将该段代码使用实际设备配套的工具链编译出相应的进程,将该进程在设备上后台运行后并可以主动去吃内存。


#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void eatMem(unsigned int block)
{
    unsigned int i;
    unsigned int j;
    unsigned int nTimes;
    char ch;
    char **pMem;

    /* 每次申请 1M */
    unsigned int cell = 1 * 1024 * 1024;
    pMem = (char **)malloc(sizeof(char *) * block);    
    for (i = 0; i < block; i++) {
        pMem[i] = (char *)malloc(cell);
        if(NULL == pMem[i]) {
            printf("Insufficient memory avalible ,Cell %d Failure\n", i);
            break;
        }

        memset(pMem[i], 0, cell);
        printf("[%u]%u Bytes.\n", i, cell);

        fflush(stdout);
        sleep(1);
    }

    /* Read & Write 100 次, 每次40秒,用来维持占有的内存一段时间 */
    for (nTimes = 0; nTimes < 100; nTimes++) {
        for(i = 0; i < block; i++) {
            printf("Read&Write [%u] cell.\n", i);
             
            if(NULL == pMem[i]) {
                continue;
            }

            for(j = 0; j < cell; j++) {
                pMem[i][j] = 'a';
                ch = pMem[i][j];
            }
            memset(pMem[i], 0, cell);

            fflush(stdout);
            sleep(1);
        }

        sleep(1);
    }

    printf("Done! Start to release memory.\n");
    //释放内存核心代码
    for(i = 0; i < block; i++) {
        printf("free[%u]\n", i);
        if(NULL != pMem[i]) {
            free(pMem[i]);
            pMem[i] = NULL;
        }  

        fflush(stdout);
        sleep(2);
    }

    printf("Operation successfully!\n");
    fflush(stdout);
}

/* gcc test.c -o test, 使用该进程时可以 ./test 30, 表示该进程主动吃30M 的内存 */
int main(int argc,charchar * args[])
{
    if (argc != 2) {
        printf("please input correct parameter\n");
        fflush(stdout);
    }

    unsigned int block = (unsigned int)atoi(argv[1]);
    printf("block is %u\n", block);
    eatMem(block);

    while (1) {
        sleep(10);
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值