假设我们具有以下结构(其中T和U是int,long,char等任何基本数据类型)
public class Acquaintance {
private String name;
private String phone;
public Acquaintance(String name, String phone) {
this.name = name;
this.phone = phone;
}
public static String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
public void printContact() {
System.out.println("Name: " + this.name + ", Phone: " + this.phone);
}
}
和另一个结构
public class Friend extends Acquaintance {
private String address;
private String birthdate;
public Friend(String name, String phone, String birthdate, String address) {
super(name, phone);
this.address = address;
this.birthdate = birthdate;
}
public void printContact() {
/* This is where I'm having trouble.
I don't know how to access the name,
and phone which are contained in the superclass.
*/
System.out.println("Name: " + "Phone: " + "Birthdate: " + this.birthdate + "Address: " + this.address);
}
}
现在我分配
struct S1 {
T t1;
U u1;
};
并且struct S2 {
T t2;
U u2;
};
被定义为
struct S1* s1 = malloc(sizeof(*s1))
如果我继续绕过container_of
,则可以完成以下操作
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) \
*__mptr = (ptr);
(type *)( (char *)__mptr - offsetof(type,member) );})
现在,我的查询假设此类操作相互遗忘(例如在不同的库中),这将导致奇怪的值修改。
上下文是:
我对S1有自己的代码,但是当我将t1传递给另一个库代码时,它具有另一个类似的结构S2,并且最终也修改了u1的值。有什么方法可以防止这种无意的用例?另外,假设在接口的每一端都有一个T* x
指针,但是出于实现它们的目的,接口实现者和接口客户端都将其存储为结构S1和S2的一部分。同样在这种情况下,可能会出现相同的情况,其中大多数服务器代码将不可更改。在这些情况下,我们如何解决这个问题?
来自内核V4L2框架here
的真实示例struct S2* s2 = container_of(x, struct S2, t2)
//Here s2->u2 is the same value as that of s1->u1
现在,我分配了如下结构:
T* x
这是static void __fill_v4l2_buffer(struct vb2_buffer *vb, void *pb)
{
struct v4l2_buffer *b = pb;
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
:
:
b->flags = vbuf->flags;
my_v4l2_driver_video_buf{
struct vb2_buffer vb;
dma_addr_t addr;
}
注意:dma_addr_t也是32位
然后我将指向vb2_v4l2_buffer
的指针传递给v4l2框架。它修改了函数struct vb2_v4l2_buffer {
struct vb2_buffer vb2_buf;
__u32 flags;
__u32 field;
struct timeval timestamp;
struct v4l2_timecode timecode;
__u32 sequence;
};
中的标志,最终我将vb
的标志设置为与结构相同的__fill_v4l2_buffer