制作可变大小结构的方法
我需要制作一个具有标头、尾部和可变长度有效负载字段的数据包。 到目前为止,我一直在使用向量作为有效负载,所以我的结构设置如下:
struct a_struct{
hdr a_hdr;
vector<unsigned int> a_vector;
tr a_tr;
};
当我尝试访问向量的成员时,我得到一个段错误,整个结构的 sizeof 给我 32 (在我添加之后)向量中大约有 100 个元素,
是一个更好的方法吗?
这 可变大小结构 C++ 他使用的是字符数组,而我使用的是向量。
I need to craft a packet that has a header, a trailer, and a variable length payload field. So far I have been using a vector for the payload so my struct is set up like this:
struct a_struct{
hdr a_hdr;
vector<unsigned int> a_vector;
tr a_tr;
};
When I try to access members of the vector I get a seg fault and a sizeof of an entire structs give me 32 (after I've added about 100 elements to the vector.
Is this a good approach? What is better?
I found this post
Variable Sized Struct C++
He was using a char array, and I'm using a vector though.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管向量类型内联在结构中,但向量中的唯一成员可能是指针。 向向量添加成员不会增加向量类型本身的大小,但会增加它指向的内存。 这就是为什么您永远不会看到内存中结构体大小增加的原因,因此您会遇到段错误。
通常,当人们想要创建一个可变大小的结构体时,他们会通过添加一个数组作为该结构体的最后一个成员并将其长度设置为 1 来实现。然后,他们将为 sizeof() 中实际需要的结构体分配额外的内存。为了“扩展”结构。 这几乎总是伴随着结构中的一个额外成员,详细说明扩展数组的大小。
使用 1 的原因在 Raymond 的博客
Even though the vector type is inlined in the struct, the only member that is in the vector is likely a pointer. Adding members to the vector won't increase the size of the vector type itself but the memory that it points to. That's why you won't ever see the size of the struct increase in memory and hence you get a seg fault.
Usually when people want to make a variable sized struct, they do so by adding an array as the last member of the struct and setting it's length to 1. They then will allocate extra memory for the structure that is actually required by sizeof() in order to "expand" the structure. This is almost always accompanied by an extra member in the struct detailing the size of the expanded array.
The reason for using 1 is thoroughly documented on Raymond's blog
其他 SO 答案中的解决方案是特定于 c 的,并且依赖于 c 数组的特殊性 - 即使在 c 中, sizeof() 也无法帮助您找到可变大小结构的“真实”大小。 本质上,这是作弊,而且是一种在C++中没有必要的作弊。
你正在做的事情很好。 为了避免段错误,请像访问 C++ 中的任何其他向量一样访问该向量:
The solution in the other SO answer is c-specific, and relies on the peculiarities of c arrays - and even in c, sizeof() won't help you find the "true" size of a variable size struct. Essentially, it's cheating, and it's a kind of cheating that isn't necessary in C++.
What you are doing is fine. To avoid seg faults, access the vector as you would any other vector in C++:
我在 boost 中看到了这个实现......它看起来真的很整洁......有一个变量
长度有效负载....
这可能与问题完全无关,但我想分享信息
i saw this implementation in boost..it looks really neat...to have a variable
length payload....
this may be totally un-related to the question, but i wanted to share the info