2

I have two cases to return the string. One returns a pointer and other returns the char array. The first case works fine while printing the string, but I am getting a segmentation fault error on the second case. I want to know why this is happening?

This is the first case, and it gives the output.

char* voice(void){
  return "hey!";
}

int main(){
printf ("%s\n", voice()); //output: hey!
return 0;
}
This is the second case, and it gives a segmentation fault.

char* voice(void){
   char str[] = "hey!";
   return str;
}

int main(){
printf ("%s\n", voice()); //segmentation fault
return 0;
}
  • The amount of implementation-specific sheer speculation or outright disinformation in at least one of the answers below is near-mind-bending. If you have a decent [book on the C language](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) you should study up on different storage mechanics, and the rules and behaviors about said-same. Specifically, *static* vs. *automatic* vs. *dynamic*. The first two are especially relevant to your question. – WhozCraig Apr 04 '19 at 03:40
  • Your compiler should have [told you why](https://ideone.com/HTTPC7). If it didn't, it's either too old or you are using it incorrectly. – n. m. could be an AI Apr 04 '19 at 03:57

2 Answers2

3

Second case does not work because you are returning address of a local array.

The scope of local array "str" is limited to the function. So the array is valid only within that function. It becomes invalid once you go out of the function. The behavior of the program will be undefined in this case.

In 1st case, you are returning address of a string constant. String constants are allocated in a separate memory space and they will be retained throughout the program. So the address of string will be still valid even after you return from voice().

MayurK
  • 1,925
  • 14
  • 27
1

In C, local arrays (like str in your second example) are by default stored in the stack section of memory. That means that the section of memory that stores str becomes unreachable as soon as voice() returns, thus producing the segmentation error when you are trying to reach unreachable memory.

String literals (like "hey") are stored in the code section of memory. Even when voice() returns, the string is still stored in the code section of memory.

AlterV
  • 301
  • 1
  • 3
  • 10