#include <stdio.h>
int main()
{
char str[11] = "HelloWorld";
printf("%s\n",str);
printf("%s\n",str+3);
/* This Line here is the devil */
printf("%s\n",str[2]); // %s needs an addr not a value.
return 0;
}
Why does that line give a segmentation fault. Is it because %s in printf needs an address and not a value.
What is the actual reason ??
str[2]returns a char, not a pointer to a char. So,printfwill try to start reading at address0x6c. Right there, there is a good chance that0x6cis an invalid address that will cause a segfault. However, if it isn’t invalid thenprintfwill keep reading until it reaches a0x00character, which very well could enter into an invalid address range.If you want to know precisely why it segfaults, you would need to follow along in a debugger, which might be interesting and educational.
If you wanted to fix the crashing line, you could change it to:
which I would consider to be better style than
str+2.