问题描述
我遇到了一个引用它的套接字编程教程
I came across a socket programming tutorial in which it is quoted
指向 struct sockaddr_in 的指针可以转换为指向 struct sockaddr 的指针反之亦然"
我不明白如何将 sockaddr_in 转换为 sockaddr.将 Big 类型的指针转换为 Small 类型应该会产生 UD 行为.
I dont understand how can sockaddr_in be cast to sockaddr. Casting a pointer of Big type to Small type should give UD behavior.
struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};
struct sockaddr_in {
short int sin_family; // Address family, AF_INET
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr
};
演员阵容如何不被定义?将这些相互投射会不会不安全?
How can the cast not be undefined? Isn't it unsafe to cast these to each other?
如果我有一个只有两个整数的 A 类和有 4 个整数的 B 类.如果我有一个 B 类型的指针并且我将它转换为 A 类型,那么确定我可以获取前两个元素.但是,如果 A 类首先声明了 2 个字符,然后声明了 2 个整数,那么指针将无法正确获取值,因为在这种情况下对象布局会有所不同.
If i have a class A having only two ints and class B having 4 ints. And if i have a pointer of type B and i cast it to type A then sure i can fetch the first two elements. But if class A has 2 chars declared first and 2 ints declared later then the pointers would not right fetch the values since the object layout in this case would be different.
编辑 1:
class Anu
{
public:
char a;
int b;
Anu()
{
a='a';
}
};
class Anurag
{
public:
Anurag() { a=4;}
int a;
int b;
int c;
int d;
};
int main()
{
Anu objanu;
Anurag objanurag;
Anurag *ptrAnurag= &objanurag;
ptrAnurag= (Anurag*)&objanu;
cout<<ptrAnurag->a; //Some weird value here
return 0;
}
假设我通过调整变量类型更改示例,使两个类具有相同的大小...即使大小保持不变,对象布局仍可能不同.
Assuming i change the example so that both classes have same size by adjusting the variables types...still the object layout might be different even though the size remains the same.
推荐答案
我会在@gsamaras 的回答中补充说,未定义的行为并不总是意味着坏事即将发生.未定义的行为实际上是说我们*没有提供任何关于如果发生 XYZ 时接下来会发生什么的规范".
I'll add to @gsamaras answer by saying that Undefined Behaviour doesn't always means that bad things are about to happen. Undefined Behaviour actually says "we* don't provide any specifications on what should happen next if XYZ occurs".
(*C++ 标准).
这是操作系统发生并说它由我们定义"的地方.
this is the place where the OS takes place and say "it is defined by us".
尽管强制转换不相关的结构(sockaddr_in
,sockaddr
)可能是标准未定义的行为,但 OS API 指定它对其 API 有效.
although casting unrelated structs (sockaddr_in
,sockaddr
) may be undefined behaviour by the standard, the OS API specify that it is valid with their API.
这篇关于sockaddr 和 sockaddr_in 之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!