Continuing from my comment:
While your technical understanding of the syntax and proper use of memory allocation functions is fine, the function you provided does not make much sense. Static declaration of local variables will always be faster (e.g. more efficient) than dynamically allocating memory (if just by virtue of saving the function call overhead).
The choice between "Do I need to dynamically allocate?" is largely governed by (1) "is it too big to fit on the stack?", and (2) "what is the lifetime needed for the stored values?" C11 Standard (draft n1570) §6.2.4 Storage durations of objects
Your function (type void
) returns no value and does nothing with the 10 int
values stored in x
. In that regard, as written, there is no need to dynamically allocate anything. Simply declaring a character array and array of long will provide automatic storage duration (e.g. for the life of function (e.g. scope) whithin which they are declared). As such, a more efficient implementation of your function would simply declare char input[32] = "";
and long x[10] = {0};
Note: when you declare arrays within a function, the memory for the array is only guaranteed to exist during the life of the funciton. Upon return, the function stack (and any variables declared local to that function) are destroyed (e.g. the memory is released for re-use), and any attempt to access the values of the array (or any variable local to that function) after the function returns results in Undefined Behavior.
Now regardless whether you return x
and change your function type to long *
, there is no need to dynamically allocate input
, as that value is not returned.
However, if you do need to return a pointer to x
so that the values you store are available back in the calling function, then you do need to dynamically allocate x
as you have done. Why? When you dynamically allocate memory for x
with malloc
the lifetime extends from the time the memory is allocated, until it is deallocated (See §7.22.3 Memory management functions, in the link above). So you can dynamically allocate x
in your function as you have done, and then declare your function as long *memoryallocationtest(int number)
and return x
to make the values available for use within the remainder of your program until you free (x);
.
Which brings me to my final point. Your function, as written, fills x
, then immediately frees x
. While fine, in a real-world use of x
, the free (x);
call would not take place until you had finished making use of x
in some meaningful way.
So in summary, there is no need to allocate for input
, if either x
won't fit on the stack, or you decide to return x;
are true, then yes, a perfectly efficient way to provide memory for x
is with malloc
. If however, you are just using x
in your function, and it will fit within the function stack, (it will until you reach several hundred thousand elements, architecture and compiler depdendent), then a simple declaration of an array of long
is all you need.