请让我知道我做错了什么。
我有两个结构
for (i = 1; i <= $scope.nDays; i++) {
var d = new Date();
d.setHours(0, 0, 0, 0);
var displayDate = new Date($scope.year, offsetDate, i);
if(displayDate >= d)
$scope.dateValues.push(displayDate);
}
我尝试这种方式,以便有效地使用struct a{
few elements;
void **ptr;
};
struct b {
few elements;
};
I tried to allocate memory for these two structures like
func2(struct a *aptr)
{
struct b *bptr = kmalloc(sizeof(struct b), GFP_KERNEL);
aptr->ptr = (void *)&bptr;
// here *(aptr->ptr) is pointing correctly to bptr.
}
func1()
{
struct a *aptr = kmalloc(sizeof(struct a), GFP_KERNEL);
func2(aptr);
/*though aptr->ptr is pointing correctly, *(aptr->ptr) is no more pointing to bptr*/
}
。
如果我的实施错误,请纠正我。
观察:如果我在函数范围之外声明container_of
,struct b *bptr
正确指向bptr。
答案 0 :(得分:2)
下面
aptr->ptr = (void *)&bptr;
指定局部变量的地址,当函数返回时超出范围。你或许是指分配bptr
而不是&bptr
吗?
答案 1 :(得分:1)
获取本地自动变量的地址并将其保存起来是错误的。你正在记住堆栈上的一些地址!
func2(struct a *aptr)
{
struct b *bptr = kmalloc(sizeof(struct b), GFP_KERNEL);
aptr->ptr = (void *)&bptr;
// here *(aptr->ptr) is pointing to bptr, which is only on the stack
// until you exit the block, then it ceases to exist and you're pointing
// to some unknown/invalid data.
}