Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1459546
  • 博文数量: 181
  • 博客积分: 3308
  • 博客等级: 中校
  • 技术积分: 2227
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-03 12:03
个人简介

我是zoro

文章分类

全部博文(181)

文章存档

2015年(1)

2013年(35)

2012年(39)

2011年(50)

2010年(56)

分类: LINUX

2010-11-15 23:26:34

例子:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/shm.h>

#define ARRAY_SIZE 40000
#define MALLOC_SIZE 100000
#define SHM_SIZE 100000
#define SHM_MODE 0644

char array[ARRAY_SIZE];    //未初始化的数据,保存在未初始化数据段

char array2[ARRAY_SIZE]={1,2,3};    //初始化的数据,保存在初始化数据段


int main(void)
{
    int shmid;
    char *ptr,*shmptr;
    char array3[ARRAY_SIZE];

    printf("array[] from %x to %x\n",(unsigned)&array[0],(unsigned)&array[ARRAY_SIZE]);
    printf("array2[] from %x to %x\n",(unsigned)&array2[0],(unsigned)&array2[ARRAY_SIZE]);
    printf("array3[] from %x to %x\n",(unsigned)&array3[0],(unsigned)&array3[ARRAY_SIZE]);
    
    printf("stack around:shmid %x,ptr %x,shmptr %x\n",(unsigned)&shmid,(unsigned)&ptr,(unsigned)&shmptr);

    if((ptr=malloc(MALLOC_SIZE))==NULL)
    {
        perror("malloc");
        exit(-1);
    }
    printf("malloc from %x to %x\n",(unsigned)ptr,(unsigned)ptr+MALLOC_SIZE);

    if((shmid=shmget(IPC_PRIVATE,SHM_SIZE,SHM_MODE))<0)
    {
        perror("shmget");
        exit(-1);
    }
    if((shmptr=shmat(shmid,0,0))==(void *)-1)
    {
        perror("shmat");
        exit(-1);
    }
    printf("shared memory attached from %x to %x\n",(unsigned)shmptr,(unsigned)shmptr+SHM_SIZE);
    if(shmctl(shmid,IPC_RMID,0)<0)
    {
        perror("shmctl");
        exit(-1);
    }
    return 0;
}

运行结果:

array[] from 8053cc0 to 805d900
array2[] from 804a060 to 8053ca0
array3[] from bf82084c to bf82a48c
stack around:shmid bf820848,ptr bf820844,shmptr bf820840
malloc from 92ed008 to 93056a8
shared memory attached from b7895000 to b78ad6a0


由结果可以看出:
全局变量存放在数据段(初始化或非初始化数据段);
普通局部变量在栈里;
malloc出的动态区域在堆中;
共享存储段紧靠在栈之下。
文件:memory.c.tar.gz
大小:0KB
下载:下载

阅读(1187) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-16 15:03:16

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com