指针地址类型检查如何工作?

How does pointer address type checking work?

我想了解在处理指针时是否有一个实现来检查 C 中特定地址处变量的类型。

假设我们有以下代码:

Car car1; // variable of type Car in memory at address 0x100
Fruit fruit1; // variable of type Fruit at address 0x104
Car *pCar1; // pointer of type Car at address 0x108

pCar1 = &car1; // The type of the pointer matches the type of the variable, nothing special

现在我尝试手动处理地址,但没有出现任何错误。但是,由于类型不匹配,程序在运行时崩溃。

pCar1 = (Car *) 0x104; // Note I am deliberately offering a Fruit address and it works without build errors

如何防止这种情况发生?是否有故障保护机制或技术来防止这种愚蠢行为?

pCar1 = (Car *) 0x104;

不允许您在此处进行的操作。您不能投射绝对地址(在您的情况下指的是不同类型)并期望它起作用。为此,您必须确保地址在运行时包含正确的变量类型。

在这种情况下,强制转换只会阻止编译警告,因为它告诉编译器 "look, I know what I'm doing, trust me, there's a Car at this address"。当然,当您的程序运行并期望在地址 0x104 找到 Car 而实际上没有时,这会导致未定义的行为。

Is there a failsafe mechanism or technique to make this stupid-proof?

绝对不是。 C 与 "stupid-proof" 相去甚远。但是,如果您将代码写在 "better way":

中,编译器会警告您
pCar1 = &fruit1; // Results in a compiler warning.

How can I prevent this from happening?

只是不要这样做。不要给变量分配随机地址或不同类型的地址。您唯一可以分配给 pCar1 的是另一个 Car 变量的地址(例如 pCar1 = &car1)或 Car 变量可以所在的内存位置的地址存储(例如适当 malloc() 的结果)。


所以,最后:

How does pointer address type checking work?

C 中没有 "address type checking" 这样的东西。只有编译器可以警告您某个变量的类型错误,如果您给它机会。显式转换会消除这种机会。