How to return a string from a C function
By Flavio
Learn how to return a string from a C function by returning a const char pointer, and why returning a local char array fails because it lives on the stack.
In one of my C programs, I had the task to return a string from a function:
xxxxx myName() {
return "Flavio";
}
The tricky thing is defining the return value type.
Strings in C are arrays of char elements, so we can’t really return a string - we must return a pointer to the first element of the string.
This is why we need to use const char*:
const char* myName() {
return "Flavio";
}
Here’s an example working program:
#include <stdio.h>
const char* myName() {
return "Flavio";
}
int main(void) {
printf("%s", myName());
}
If you prefer to assign the result to a variable, you can invoke the function like this:
const char* name = myName();
We can write the pointer operator * also in this ways:
const char * myName()
const char *myName()
All forms are perfectly valid.
Note the use of const, because from the function I’m returning a string literal, a string defined in double quotes, which is a constant.
Note that you can’t modify a string literal in C.
Another thing to keep in mind is that you can’t return a string defined as a local variable from a C function, because the variable will be automatically destroyed (released) when the function finished execution, and as such it will not be available, if you for example try do do:
#include <stdio.h>
const char* myName() {
char name[7] = "Flavio";
return name;
}
int main(void) {
printf("%s", myName());
}
you’ll have a warning, and some jibberish, like this:
hello.c:5:10: warning: address of stack memory
associated with local variable 'name'
returned [-Wreturn-stack-address]
return name;
^~~~
1 warning generated.
B��Z> K���⏎
Notice the B��Z> K���⏎ line at the end, which indicates that the memory that was first taken by the string now has been cleared and there’s other random data in that memory. So we don’t get the original string back.
Changing myName() to
const char* myName() {
char *name = "Flavio";
return name;
}
makes the program work fine.
The reason is not the heap. "Flavio" is a string literal. It lives in static (read-only) storage for the whole program run, so returning a pointer to it is fine. Nothing goes on the heap unless you malloc() it.
Writing to a string literal is undefined behavior. That is why const char* is the right return type. If you need a modifiable string, use malloc() (the caller frees it) or a static char array. I cover static in static variables.
Want me to talk about your product? You can sponsor this site.