I\'m having trouble return a string from a function. It prints out a garbage value in the main method. I saw a similar question on this forum but the results on that page didn\'
You cannot return a local array (like your path_name
) from a function. That local array is inside the call frame, which gets popped on return.
As others replied, you should do
strncpy(result, path_name, MAX_PATH_LEN);
and document the convention that the caller should free the result.
BTW, your code is quite inefficient; you are allocating a rather large chunk of MAX_PATH_LEN
(often 4096) for a string which often is much smaller.
If using GNU extensions you could simply use asprintf(3) (see this) or at least remove your malloc
and return strdup(path_name);
and use strdup(3) (which is standard, not requiring any GNU extension).
And learn how to use valgrind.