如何有效地使用双void指针

时间:2015-10-20 13:05:07

标签: c linux-device-driver

请让我知道我做错了什么。

我有两个结构

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_ofstruct b *bptr正确指向bptr。

2 个答案:

答案 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.
}
相关问题