Saturday, 3 June 2017

c - When is it necessary to allocate dynamic memory using malloc on pointers?




I am having trouble fully understanding the malloc() function in C, more precisely when it is necessary to use it.



When I declare a pointer to a global struct like so,



struct Position* currentPositionPtr;


do I need to assign dynamic memory to it using malloc to initialize it?
Or is it good practice to simply assign a pointer of the struct to it later on when needed like e.g.




currentPositionPtr = getPosition();


where getPosition() returns a pointer to the "struct Position".


Answer



What does getPosition() do?



If it returns a valid pointer to struct Position, then of course you don't need to allocate memory for the struct twice. I hope your function does not look like this:



struct Position *getPosition()

{
struct Position p = { x, y };
return &p;
}


since this would exhibit undefined behavior (by returning a pointer to a block scope automatic object). Generally, you rather return an already malloc()ated pointer instead:



struct Position *getPosition()
{

struct Position *p = malloc(sizeof(*p));
p->x = 42;
p->y = 1337;
return p;
}


Then, again, you don't need an additional call to malloc().



If, however, it's not the called function who is responsible for the allocation, then, well... it's the caller who is:




void getPosition(struct Position *p)
{
p->x = 42;
p->y = 1337;
}


And in this latter case you would need to call it like this:




struct Position *p = malloc(sizeof(*p));
getPosition(p);


if you need your struct to survive function returns, or



struct Position p;
getPosition(&p);



if you don't.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...