gpt4 book ai didi

c++ - 将 char 地址分配给 int 指针,然后写入 int 大小的内存块

转载 作者:行者123 更新时间:2023-12-01 15:10:14 24 4
gpt4 key购买 nike

来自Stroustrup - 编程:使用 C++ 的原则和实践一书。在§17.3中,关于内存、地址和指针应该允许分配一个char*int*:

char ch1 = 'a';
char ch2 = 'b';
char ch3 = 'c';
char ch4 = 'd';
int* pi = &ch3; // point to ch3, a char-size piece of memory
*pi = 12345; // write to an int-size piece of memory
*pi = 67890;

我们有这样的图形:

char address to int pointer

引用来源:

Had the compiler allowed the code, we would have been writing 12345 to the memory starting at &ch3. That would definitely have changed the value of some nearby memory, such as ch2 or ch4, or we would have overwritten part of pi itself.

In that case, the next assignment *pi = 67890 would place 67890 in some completely different part of memory.


我不明白,为什么下一个作业会把它放在:内存的某个完全不同的部分int *pi 中存储的地址仍然是 &ch3,因此分配将覆盖该地址的内容,即 12345。为什么不是这样?

拜托,你能帮帮我吗?非常感谢!

最佳答案

char ch3 = 'c';
int* pi = &ch3;

it is supposed to be allowed to assign a char* to int*:

不完全 - 存在对齐问题。这是未定义的行为(UB)当

If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. C17dr § 6.3.2.3 7

示例:某些处理器要求 int * 为偶数,如果 &ch3 为奇数,则存储地址 可能 失败,并取消引用地址肯定失败:bus error .


下一个肯定是UB,因为目的地在ch3的内存之外。
ch1, ch2, ch4 可能在附近并提供一些合理的未定义行为,但结果是 UB。

// undefined behavior
*pi = 12345; // write to an int-size piece of memory`

当代码尝试写入其边界之外 - 它是 UB,任何事情都可能发生,包括写入相邻数据。

The address stored in int *pi is still &ch3

也许,也许不是。发生了 UB。

why the next assignment would place it: in some completely different part of memory?

滥用代码表明 pi 本身被 *pi = 12345; 覆盖。这可能会发生,也可能不会。是UB。 *pi 的后续使用只是更多的 UB。


回想一下 UB,你可能会得到你希望的东西,你可能不会 - 它不是由 C 定义的。

关于c++ - 将 char 地址分配给 int 指针,然后写入 int 大小的内存块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63400265/

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