In the program below, the function getcc() returns pointer to a char array that was allocated inside getcc(). When I pass that pointer in printf with %s format specifier, it does not print anything.
#include<stdio.h>
char* getcc();
int main(){
char *cp = getcc();
printf("%s",cp);
}
char* getcc(){
char c_arr[] = "cow";
return c_arr;
}
However, when the char array is made into an external variable, it works as expected and prints the word cow.
#include<stdio.h>
char* getcc();
int main(){
char *cp = getcc();
printf("%s",cp);
}
char c_arr[] = "cow";
char* getcc(){
return c_arr;
}
Output
cow
Also, if I try to print the individual chars with "%c" format specifier, it is working as expected.
#include<stdio.h>
char* getcc();
int main(){
char *cp = getcc();
printf("%c%c%c",*cp,*++cp,*++cp);
}
char* getcc(){
char c_arr[] = "cow";
return c_arr;
}
Output
cow
What is the reason behind this phenomenon?
c_arr
is freed whengetcc()
returns, and you are now operating with a pointer to freed memory.