当前位置:  开发笔记 > 运维 > 正文

每次在C中执行程序时指针地址是否会改变?

如何解决《每次在C中执行程序时指针地址是否会改变?》经验,为你挑选了1个好方法。

我试图理解指针,我遇到了这段代码,每当我编译并执行它时,地址就会改变.它是一些垃圾值还是指针实际上是在运行中分配的内存?

我的命令提示符:

kaushik@IntelliBox:~/Desktop/Learn_C$ ./Practice
nNUmber is equal to : 15
nNumber is equal to : 25
0xbf98fd64

kaushik@IntelliBox:~/Desktop/Learn_C$ make Practice
make: 'Practice' is up to date.

kaushik@IntelliBox:~/Desktop/Learn_C$ ./Practice
nNUmber is equal to : 15
nNumber is equal to : 25
0xbfcce2a4

kaushik@IntelliBox:~/Desktop/Learn_C$ ./Practice
nNUmber is equal to : 15
nNumber is equal to : 25
0xbfa25df4

kaushik@IntelliBox:~/Desktop/Learn_C$ ./Practice
nNUmber is equal to : 15
nNumber is equal to : 25
0xbfecf104

我的C代码是:

#include 

int main()
{
    int nNumber;
    int *pPointer;

    nNumber = 15;
    pPointer = &nNumber;

    printf("nNUmber is equal to : %d\n", nNumber );

    *pPointer = 25;

    printf("nNumber is equal to : %d\n", nNumber );

    printf("%p\n", pPointer );

    return 0;
}

先感谢您.



1> P.P...:

表示或确切构成指针值的是实现细节。C标准没有规定任何要求。不能保证每次运行代码时该值是相同还是不同。

C标准仅定义有效指针之间的指针算术(例如,比较数组对象中的两个指针)。

顺便说一句,您应该按照C标准的要求将指针强制转换void*为print %p

printf("%p\n", (void*) pPointer );

如评论中所述,某些操作系统确实解决了空间布局的泛化问题。Linux默认情况下会这样做。对于您的代码,我通过ASLR得到以下输出:

$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffde18ba7c
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fff981efe0c
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7ffdade6837c
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7ffced208b4c

如果我通过以下方式禁用它:

echo 0 > /proc/sys/kernel/randomize_va_space

然后输出相同的值:

$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec
$ ./a.out
nNUmber is equal to : 15
nNumber is equal to : 25
0x7fffffffeaec

但是就C标准而言,绝对不能保证这些值。

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有