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: