Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to member of struct using double pointer

I have a function that takes a double pointer to a struct and assigns a value. However I get an "access violation writing location ..." when trying to access the member member1. This is my code:

struct mystruct{
  unsigned int member1;
  void * data;
};

int main(){

  mystruct **foo = new mystruct *;
  bar(foo);

}

void bar(unsigned int val, mystruct ** foo)
{
    (*foo)->member1 = val;
}
like image 679
tzippy Avatar asked Oct 01 '13 08:10

tzippy


2 Answers

You just created a new mystruct pointer. That means:

You get allocated a memory block, large enough to hold a address, and assign it to the pointer which is pointing to a pointer that points to a mystruct member. That doesn't mean, that there is a valid address hold in the pointer which you expect to be pointing to a mystruct element. Even more currently there isn't even a valid address, where the pointer to the pointer is pointing on, as you just assigned a valid memory area to it, what doesn't mean there is a usefull address stored in.

So at all, what you want is:

You want a pointer which has a valid memory block to store a address in of another pointer, which is pointing to a valid memory area, where is a (probably valid) mystruct stored in.

What you are doing is: you are requesting a memory area where you COULD (what you aren't even doing) store a poitner to another pointer... and so on.

so what you should do is:

mystruct **foo = new mystruct *;
*foo = new mystruct;
like image 155
dhein Avatar answered Sep 20 '22 02:09

dhein


I have a function that takes a double pointer

That's weird. If you can, simplify it to take a reference:

void bar(unsigned int val, mystruct & foo) {
    foo.member1 = val;
}

mystruct foo;
bar(42, foo);

If you don't have control over the function, then you'll need an object at the end of the pointer trail:

mystruct foo;
mystruct * pointless = &foo;
bar(42, &pointless);

You can, of course, mess around with new if you really want to; but that's almost certainly a bad idea.

Your code allocates and leaks a pointer, but doesn't initialise it to point to a valid object; so dereferencing it gives undefined behaviour.

like image 36
Mike Seymour Avatar answered Sep 19 '22 02:09

Mike Seymour