APUE第15章学习扎记之程序的存储区布局试验

[root@localhost apue.2e]# cat apue15.11.c
#include "apue.h"
#include <sys/shm.h>

#define    ARRAY_SIZE    40000
#define    MALLOC_SIZE    100000
#define    SHM_SIZE    100000
#define    SHM_MODE    0600    /* user read/write */

char    array[ARRAY_SIZE];    /* uninitialized data = bss */
static int arraystatic[ARRAY_SIZE] = {0};

int uninitdata;
int initdata = 1;

static int printString(void)
{
    
    printf("hello guy!!!\n");
    return 1;
}

int
main(void)
{
    int        shmid;
    char    *ptr, *shmptr;
    static int testStatic = 0;
    auto int testAuto = 1;    

    printf("array[] from %lx to %lx\n", (unsigned long)&array[0],
      (unsigned long)&array[ARRAY_SIZE]);
    printf("stack around %lx\n", (unsigned long)&shmid);

    if ((ptr = malloc(MALLOC_SIZE)) == NULL)
        err_sys("malloc error");
    printf("malloced from %lx to %lx\n", (unsigned long)ptr,
      (unsigned long)ptr+MALLOC_SIZE);
    
    printf("static data in %lx\n", (unsigned long)&testStatic);

    printf("auto data in %lx\n",(unsigned long)&testAuto);

    if ((shmid = shmget(IPC_PRIVATE, SHM_SIZE, SHM_MODE)) < 0)
        err_sys("shmget error");
    if ((shmptr = shmat(shmid, 0, 0)) == (void *)-1)
        err_sys("shmat error");
    printf("shared memory attached from %lx to %lx\n",
      (unsigned long)shmptr, (unsigned long)shmptr+SHM_SIZE);

    if (shmctl(shmid, IPC_RMID, 0) < 0)
        err_sys("shmctl error");

    int prt = printString();
    printf("uninitdata address is : %lx\n",(unsigned long)&uninitdata);
    printf("initdata address is : %lx\n",(unsigned long)&initdata);
    printf("printString address is : %lx\n",(unsigned long)&printString);
    
    printf("static array initdata address is from %lx  to  %lx \n",(unsigned long)&arraystatic[0],(unsigned long)&arraystatic[ARRAY_SIZE]);

    exit(0);
}


运行结果为:

[root@localhost apue.2e]# ./apue15.11.o
array[] from 6289a0 to 6325e0
stack around 7fff37c612b4
malloced from 1a7d010 to 1a956b0
static data in 628980
auto data in 7fff37c612b0
shared memory attached from 7f6af5f06000 to 7f6af5f1e6a0
hello guy!!!
uninitdata address is : 6325e0
initdata address is : 60183c
printString address is : 400f6f
static array initdata address is from 601880  to  628980

分析上面所有在存储区的结构分配。。。。

你可能感兴趣的:(内存,栈,堆,apue,程序段)