Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
Is it possible to return a local array in c ? i dont think so .
Doing a malloc and returning the ptr would work but it would lead to a memory leak .
Nope my friend....the caller who receives the malloc'ed memory has to free it.
You may want to dig a bit more into usage of malloc. I would recommend a small dig into Unix process layout...if you can find somebody who has worked on Unix internals, it would help to have a discussion on how memory allocation is implemented.
The interviewer insisted that a local array can be returned in C (without returning the ptr to the array) . However , i was not convinced as return of arrays is supported in Java , python etc where the garbage collection is automatically done . But i think it is not possible in C or CPP
It is possible to return an array in c. Below is the function prototype .
Char [] replace_string( char const *const str )
Inside the function you can declare the array as static and return the array or can dynamically allocate memory for array.
another way you could return the array as a parameter in the function
Static void replace_str(char const *const str, char dst[length] )
Question needs some clarification.
- Anonymous December 30, 2012The input string cannot be modified as the replacement word can be a different size than the word it is replacing. So, implicitly, it needs new string memory.
As you specify, we cannot allocate a local variable and return. So, why not use malloc i.e. dynamic memory allocation and return the pointer?