For starters this program
void newArray(int* local, int size)
{
local = (int*) malloc( size * sizeof(int) );
}
int main() {
int* ptr;
newArray(ptr, 10);
}
demonstrates that who asked the question in the interview is not strong himself as a C programmer.
First of all, according to the C Standard, function main
without parameters shall be declared like
int main( void )
Secondly there is not any reason to declare the second parameter of the function newArray
as having the type int
instead of the type size_t
because the standard function malloc
used in the function has a single parameter of the type size_t
.
Otherwise the function should check that the argument passed to the function is not a negative value.
As for the question then function parameters are its local variables. They are initialized by the supplied arguments. You can imagine the function definition and its call the following way
newArray(ptr, 10);
// ...
void newArray( /* int* local, int size */ )
{
int *local = ptr;
int size = 10;
local = (int*) malloc( size * sizeof(int) );
}
As you can see it is the parameter (that is a local variable) local
that is changed inside the function. The argument itself stays unchanged. Only the value of the argument is used to initialize initially the parameter. After exiting the function its local variables (including its parameters) are not alive and destroyed.
So the function indeed has a memory leak.
You should pass the argument by reference if you want that its value was changed in the function. For example
void newArray( int **local, size_t size )
^^^^^^^^^^^^^^^^^^^^^^^^
{
*local = (int*) malloc( size * sizeof(int) );
}
And the function should be called like
newArray( &ptr, 10 );
However a question arises what to do with the value of the pointer *local
before reassigning it. Whether there should be called the function free
before the call of malloc or not.
So a more clear function definition can look like
int * newArray( size_t size )
{
return malloc( size * sizeof( int ) );
}
In this case it is the client of the function who decides what he should do with his own pointer which he is going to reassign.