Question:
Why am I getting Segmentation Fault 11 in this C code?
Elephant
2012-08-17 07:01:53 UTC
Hi I am pretty new to C, and I wanted a simple code to read input and then print it out. This is what I had:

#include
main(){
char *str;
printf("Enter the string: ");
scanf("%s",str);
printf("\n%s\n",&str[1]);
}

For some reason, I keep getting Segmentation Fault: 11. Help!
Three answers:
roger
2012-08-17 07:25:43 UTC
include

main(){

char *str; // here is the problem

str is a pointer to char -- it does not point anywhere

you need to give it somewhere to point



that is: str is a variable that CAN hold the starting addresss of a string of characters

you have not given it any value yet so it could point ANYWHERE!



printf("Enter the string: ");

scanf("%s",str);

printf("\n%s\n",&str[1]);

}



#include

#include

int main(void){ // since main() returns an int say so

char *str;

str=malloc(100); // make it point somewhere

printf("Enter the string: ");

scanf("%s",str);

printf("\n%s\n",&str[1]); // this is ok

// &str[1] is the starting address of the second letter that you entered via scanf()

return 0;

}

// 'cause main() returns an int return one
green meklar
2012-08-17 18:56:27 UTC
You never initialized str. As a result, it has a garbage value and points to some unknown place in memory. When you try to fill that memory block with user input, it's not surprising that you end up getting a segmentation fault.



To fix it, try allocating some memory and setting str to point there.
Limesticks
2012-08-17 07:10:30 UTC
This line is wrong:

printf("\n%s\n",&str[1]);



&str[1] doesn't really make sense. First of all, str is not an array, but an pointer. Second of all, you don't need to use &.



This line of code will work:

printf("%s", str);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...