一段关于C内存分配的奇怪代码

来源:互联网 发布:如何打底妆 知乎 编辑:程序博客网 时间:2024/06/06 14:03

下面的代码在linux环境下(2.6.16.21),gcc(gcc (GCC) 4.1.0 (SUSE Linux))编译,输出很奇怪,不知道是怎么回事?

为什么只修改pStrName3的大小,就会导致pStrName3和pStrName4分配内存顺序发生变化??

搞不明白C是怎么样管理栈上的内存分配的,百思不得其解,还望高人指点一下!

#include <stdio.h>
#include <string.h>
#include <sys/types.h>


int main(int argc, char **argv)
{
        char pStrName1[] = "独孤剑";
        char pStrName2[] = "令狐冲";
        int iStep = pStrName2 - pStrName1 ;
        printf("pStrName2 is %x, pStrName1 is %x, iStep is :%d/n",pStrName2, pStrName1, iStep);

        //大小为32时,iStep为32 大小为16时 iStep=-15 ???
        //char pStrName3[32]="1234567890123456789012345678901";
        char pStrName3[16]="123456789012345";
        char pStrName4[15]="abcdefghijklmn";
        iStep = pStrName4 - pStrName3 ;
        printf("pStrname4 is %s, pStrName3 is %s/n", pStrName4, pStrName3);
        printf("pStrName4 is %x, pStrName3 is %x, iStep is :%d/n",pStrName4, pStrName3, iStep);

//        char p[32]="abcd""efgH";
//        printf("p is %s/n", p);

}

                       
=========================
testUser@tencent:~/CPP_Prog/test$ g++ -o str str.cpp
testUser@tencent:~/CPP_Prog/test$ ./str
pStrName2 is bfabfe8e, pStrName1 is bfabfe95, iStep is :-7
pStrname4 is abcdefghijklmn, pStrName3 is 1234567890123456789012345678901
pStrName4 is bfabfe7f, pStrName3 is bfabfe5f, iStep is :32
p is abcdefgH

修改了pStrName3为[16]之后的结果:
testUser@tencent:~/CPP_Prog/test$ g++ -o str str.cpp
testUser@tencent:~/CPP_Prog/test$ ./str
pStrName2 is bf8ae47e, pStrName1 is bf8ae485, iStep is :-7
pStrname4 is abcdefghijklmn, pStrName3 is 123456789012345
pStrName4 is bf8ae45f, pStrName3 is bf8ae46e, iStep is :-15
p is abcdefgH 

原创粉丝点击