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

下面的代码在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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值