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.