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
You are returning a pointer to local data, which is not valid after the function returns. You have to allocate the string properly.
This can be done in either the calling function, by supplying a buffer to the called function, and it copies the string over to the supplied buffer. Like this:
char segmentFileName[SOME_SIZE];
getSegmentFileName(file, lineLength, mid, segmentFileName);
and the getSegmentFileName
function:
void getSegmentFileName(FILE *file, int lineLength, int lineNumber, char *segmentFileName)
{
/* ... */
strcpy(segmentFileName, fileNameString);
}
The other solution is to allocate the memory for the string in getSegmentFileName
:
return strdup(fileNameString);
but then you have to remember to free
the string later.