Returning a char pointer in C
Solution 1
Follow George Skoptsov
recommendations. But If you don't have the strdup()
function,then use this:
char* strdup(const char* org)
{
if(org == NULL) return NULL;
char* newstr = malloc(strlen(org)+1);
char* p;
if(newstr == NULL) return NULL;
p = newstr;
while(*org) *p++ = *org++; /* copy the string. */
return newstr;
}
And then:
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */
/* do something... */
char* ListFiles() {
/* .... */
return strdup(f);
}
Or instead of char file[30];
do a dynamic memory allocation
: char* file = malloc(30);
then you can do return f;
and it will work fine because f
now is not a pointer to a local variable.
Solution 2
What you're doing is returning a pointer to a local variable, which used to be allocated on stack.
Change your return statement to
return strdup(file);
Solution 3
file
is a stack variable in ListFiles()
and you're returning a pointer to it. Once you return from that function, the variable will cease to exist, so the returned pointer will be invalid.
If you want to return a string, you should allocate it on the heap, return it, use it, then free it once you're done using it.
Solution 4
You are returning a pointer points to the stack variable. When the function returns, the stack gets popped off. The stack variable no longer exists, the pointer become a dangling pointer.
One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function.
panda
Updated on July 10, 2020Comments
-
panda almost 4 years
I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below
char* ListFiles(){ FILE *fp; char file[30]; char *f; if((fp=fopen("list","r"))==NULL) { ... } while (!feof(fp)) { fgets(file,50,fp); } fclose(fp); f=file; printf("%s",f); //get display!!! return f; } int main(){ char *files; ... ... files=ListFiles(); printf("%s",files); //nothing display!! sent(); }
However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work.
-
Mr Lister about 12 years
strdup
is not a standard function, it's only defined in MSVC. -
ouah about 12 yearsscope and storage duration are two different beasts.
-
Jack about 12 years@MrLister: It's available in
POSIX
environment as well. -
Mr Lister about 12 yearsEven if you don't have
strdup
, you always havestrcpy
when including<string.h>
... -
Joniale over 6 yearsHere a good example on how to do different things with strings and pointers in C stackoverflow.com/a/46344713/5842403