Returning a string from a function in C

前端 未结 7 1106
耶瑟儿~
耶瑟儿~ 2020-12-18 07:28

I have a c function that I want to return a string.

If I print the string before it is returned then I see croc_data_0186.idx

If I try and print the string

7条回答
  •  猫巷女王i
    2020-12-18 07:55

    This is because you are returning a pointer to local. This is undefined behavior.

    strtok returns a pointer into the line character array. You put that pointer into fileNameString, and return to the caller. At this time the memory inside line becomes invalid: any garbage can be written into it.

    To avoid this problem, you should either pass a buffer/length pair for the return value, or use strdup() on the string that you are returning. In the later case you should remember to free the memory allocated for the returned string by strdup().

    On a related subject, you should avoid using strtok, because it is not re-entrant, and will cause issues in multithreaded environments. Consider using strtok_r instead.

提交回复
热议问题