When actually using malloc () and / or calloc ()?

0

My doubt is that you are learning from banal examples (as I see it), as in: int *ptr; ptr = malloc(sizeof(int));

I find it useless to allocate a space from an integer to an integer pointer, does it not do it alone anymore?

When do I actually use these dynamic memory allocation functions? If you can give examples, it would be of great value.

    
asked by anonymous 04.12.2018 / 01:30

1 answer

1

I could have done that which is easier, right?

int *ptr = malloc(sizeof(int));

So it seems to me that the biggest problem is to be coding without really understanding what's going on there.

We can not say without a larger context if this is really necessary. It is even possible for a very basic exercise just to show malloc() in action makes some sense, but for use in real application really should not be used in most cases.

Is there any reason to allocate the integer in heap ? It's unlikely. Its size is small, and if the die survives the lifetime of the function it is created the easiest is to return that value or return it through a parameter by reference, but not to allocate dynamically. Allocate with malloc() will oblige you in normal conditions to give a free() , who receive this amount must comply with the agreement of release. It does not pay for something so simple.

Examples of cases and reasons for using these functions have already been answered:

04.12.2018 / 01:48