-4

When I compile my C codes sometimes I get this error message.

Mycode.exe has stopped working..
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution available.

My C code :

#include<stdio.h> 

main(){ 
    char a; 
    a="S"; 
    printf("%s",a); 
} 

So what is the reason for this problem?
Syntax error, Runtime error or another reason?

dvhh
  • 4,724
  • 27
  • 33
  • Please share your code or ask something more specific. – Marievi Jul 20 '16 at 08:37
  • #include main(){ char a; a="S"; printf("%s",a); } – Gayantha Akalanka Jul 20 '16 at 08:38
  • 1
    It means (a) you're not just compiling and linking your program; you're also running it. And (b) your program is invoking *undefined behaviour* that is fortunately causing early termination by the OS. The code you just posted does just that. That code suggests a [good book on the C language](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list?s=1|3.4128) is a sound investment. – WhozCraig Jul 20 '16 at 08:39
  • @WhozCraig So isn't there a way to compile my code ? – Gayantha Akalanka Jul 20 '16 at 08:42
  • As I said, your code is compiling *and* running. It's just plain bad code that invokes undefined behavior. Thus the suggestion for a book on the language. (and that code belongs in *your question*; not in a comment down here. And for goodness sake, *turn up your warning levels on your compiler*. – WhozCraig Jul 20 '16 at 08:47
  • @WhozCraig ok..Thank you for your help! :D – Gayantha Akalanka Jul 20 '16 at 08:51
  • 1
    Please turn on/up compiler warnings! Your code should give 2 warnings, one for assignment of incompatible types (assigning a string to a char) and one for improper format code (printing a char with "%s"). – Klas Lindbäck Jul 20 '16 at 08:54

2 Answers2

1

When you invoke printf with %s it means that printf will start printing at the given address and end when a null terminator is reached, because you are giving printf a char and not a pointer to a char, it tries to use the value written in a to start printing from.

a is a char taking up a space of one Byte while an address is 8 Bytes in a 64 bit system, so basically printf takes the value in 'a' and the the next 7 Bytes(which are random 'garbage') and tries to use it as an address to stop printing.

that is why it sometimes works as you said, sometimes those random addresses are fine to start printing from, but sometimes they are addresses that you are not authorized to access like areas of memory used by the OS or kernel.

to solve the problem you need to make a a char * and not a char, and assign it with a string.

dvhh
  • 4,724
  • 27
  • 33
monkeyStix
  • 620
  • 5
  • 10
-1

Change your code to

#include<stdio.h> 
int main()
{ 
  char a; 
  a='S'; 
  printf("%c",a);
  return 0;
 } 

and it will work fine.

Govind Madhu
  • 182
  • 1
  • 9