Reputation: 857
I am running a very straightforward executable compiled with MinGw, and Windows 10 gives me an error stating that the program stopped. Here is the debug session:
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from c:\Users\sansari\Documents\source\chapt11\Aa.exe...done.
(gdb) b 2
Breakpoint 1 at 0x40141e: file Aa.c, line 2.
(gdb) run
Starting program: c:\Users\sansari\Documents\source\chapt11/Aa.exe
[New Thread 8756.0x2c54]
[New Thread 8756.0x15d8]
Breakpoint 1, main () at Aa.c:4
4 char s[] = "Aw what the heck";
(gdb) n
5 printf ("\n%s", s);
(gdb) n
Aw what the heck6 printf ("\n%s", s[3]);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x74cfb180 in ungetwc () from C:\WINDOWS\SysWOW64\msvcrt.dll
(gdb)
I do not know how to fix this or what else to look into. I did an online search about the error and found this bug, but this was from 2013, and by now I am sure the patch is included. I did send an email to the group about it anyway.
I also found this link, and scanned my machine with "sfc /scannow" command, and scan came back with no issues. The only thing I have not done is to reinstall this file. Is there anything I can do to fix this issue?
Upvotes: 0
Views: 3574
Reputation: 29012
The error is in your code. msvcrt.dll
(the library which provides you the function printf
) is only crashing because you fed it wrong parameters and trying to use them, it gets bitten and now it looks like it is the culprit - but actually it's you. It's like giving your friend the police's phone number and telling him it's the pizza service and he should order some pizza there, and then the police makes him pay a fine for the alleged "prank call". In this case the fine is a crash.
The issue lies here:
printf ("\n%s", s[3]);
%s
expects a string pointer as parameter. You are feeding it a character. The 4th character in your string is a w
which has ASCII code 119
or 0x77
in hex, and printf
will believe this is a memory address, so it will now try reading from memory address 0x00000077
which can't work and makes it crash!
What you need is %c
which will print a single character (by value):
printf ("\n%c", s[3]);
What I mean by "by value": You are still passing exactly the same value, 119
. It's just that you now tell printf
to treat it as a character's ASCII value (%c
), which will get correctly interpreted as a w
character, and not as a memory address pointing to a string (%s
).
Upvotes: 3
Reputation: 409166
Because s[3]
is not a string, it's a single character. The printf
function thinks that the single character (most likely a single byte) is a pointer to a zero-terminated sequence of character, which it isn't and you will have undefined behavior.
To print a single character you should be using the "%c"
format. See this printf
(and family) reference for more information and a table of all formats.
Upvotes: 1