您的位置:首页 > 编程语言

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

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

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

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  进程 内存
相关文章推荐