您的位置:首页 > 运维架构 > Linux

Linux_ 内存管理demo

2016-03-31 13:15 316 查看
main1.c

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
char *buff;
void *buff2;

buff = malloc(1024);   // ∏≥÷µ ±Ω¯––¡À¿‡–Õ◊™ªª
//µ»Õ¨”⁄:  buff = (char*)malloc(1024);

printf("buff addr is %p \n", buff);

sprintf(buff, "hello !\n");
printf("buff: %s", buff);

buff2 = malloc(1024);
//int x = *buff2;     // ≤ªƒ‹÷±Ω”∂‘void*÷∏’ÎΩ¯––∂¡–¥£¨–Ë“™œ»Ω¯––¿‡–Õ◊™ªª°£
return 0;
}


main2.c

#include <stdio.h>
#include <stdlib.h>

#define MEM_SIZE    (1024*2)    /*UNIT: M*/

int main(void)
{
char *buff;
int count = 0;

while (count++ < MEM_SIZE) {
buff = (char*)malloc(1024*1024);
if (buff) {
sprintf(buff,  "hello");
printf("malloc %d M bytes memory!\n", count);
} else {
printf("malloc faile!\n");
break;
}
}

return 0;
}


main3.c

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *buff;
int count = 0;

while (1) {
buff = (char*)malloc(1024*1024);
if (buff) {
sprintf(buff,  "hello");
printf("malloc %d M bytes memory!\n", ++count);
} else {
printf("malloc faile!\n");
break;
}
}

return 0;
}


main4.c

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
char *buff;
char *p;

buff = (char*)malloc(1024);
*(buff+1025) = 0;

p = buff + 1025;
while (1) {
*p = 0;
p++;
}

return 0;
}


main5.c

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char *p = 0;

*p = 1;

return 0;
}


main6.c

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char * buff;
char *p;

buff = (char*)malloc(1024);
p = buff + 1;

//free(buff);
free(p);        //Ω´≤˙…˙∂Œ¥ÌŒÛ

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: