C String Return Function Returns Garbage

后端 未结 4 1109
夕颜
夕颜 2021-01-27 09:44

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\'

4条回答
  •  面向向阳花
    2021-01-27 10:32

    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.

提交回复
热议问题