gpt4 book ai didi

c - 每次在 C 中执行程序时,指针地址都会改变吗?

转载 作者:太空狗 更新时间:2023-10-29 15:02:02 26 4
gpt4 key购买 nike

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

我的命令提示符:

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 <stdio.h>

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;
}

提前谢谢你。

最佳答案

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

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

顺便说一句,您应该将指针转换为 void* 以按照 C 标准的要求使用 %p 进行打印:

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

如评论中所述,某些操作系统会执行 address space layout randamization . 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 标准而言,绝对不能保证值。

关于c - 每次在 C 中执行程序时,指针地址都会改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com