Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANSI C do you have to use malloc() when creating a struct?

Let's say I have this struct in ANSI C:

typedef struct _point
{
    float x;
    float y;
} Point;

and this function to create this struct:

Point createpoint(float x, float y)
{
    Point p;
    p.x = x;
    p.y = y;
    return p; 
}

This allows me to create a struct with this function i.e:

int main()
{
    Point pointOne = createpoint(5, 6);  
    Point pointTwo = createpoint(10, 4);
    float distance = calculatedistancefunc(pointOne, pointTwo);

    /* ...other stuff */

    return 0;
}

Someone told me that this code is not valid, because the struct does not get malloc'd in the createpoint(float x, float y) function before it gets returned, and that the struct will be deleted. However, when I use my struct like this, it doesn't seem to get deleted.

So my question is: do I have to malloc this struct, and why? / why not?

like image 384
Marnix v. R. Avatar asked Oct 05 '11 05:10

Marnix v. R.


People also ask

Does declaring a struct allocate memory in C?

This tells the compiler how big our struct is and how the different data items (“members”) are laid out in memory. But it does not allocate any memory. To allocate memory for a struct, we declare a variable using our new data type.

What happens when you malloc a struct?

malloc allocates sizeof(struct node) bytes, and returns a void pointer to it, which we cast to struct node *. Under some conditions malloc could fail to allocate the required space, in which case it returns the special address NULL.

Can you allocate memory in a struct?

Example: Dynamic memory allocation of structs In the above example, n number of struct variables are created where n is entered by the user. To allocate the memory for n number of struct person , we used, ptr = (struct person*) malloc(n * sizeof(struct person));

Does typedef statement allocate memory?

The typedef statement itself allocates no memory. A variable declaration is required to allocate storage space for a structured data object.


1 Answers

Whatever you are doing is entirely correct. The statement -

return p;

in the function returns a copy of the local variable p. But if you want the same object that was created in the function, then you need to malloc it. However, you need to free it later.

Point createpoint(float x, float y)
{
    Point p;
    p.x = x;
    p.y = y;
    return p; 
} // p is no longer valid from this point. So, what you are returning is a copy of it.

But -

Point* createpoint(float x, float y)
{
    Point *p = malloc(sizeof(Point));
    p->x = x;
    p->y = y;
    return p; 
}// Now you return the object that p is pointing to.
like image 156
Mahesh Avatar answered Oct 06 '22 20:10

Mahesh