小编bem*_*m22的帖子

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

我试图了解是否存在一种在处理指针时检查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
Run Code Online (Sandbox Code Playgroud)

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

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

如何防止这种情况发生?有没有使这种愚蠢的失败保护机制或技术?

c pointers undefined-behavior

-1
推荐指数
1
解决办法
60
查看次数

标签 统计

c ×1

pointers ×1

undefined-behavior ×1