The problem is that your variables are declared as char
, but you read as int
. Thus, the scanf
function reads more than 1 byte and invades the memory of the x2
variable (which as it was declared after, it is immediately in memory).
Using Visual Studio, for example, you can see that the memory addresses of each of the variables is followed (% with% in 0x00ff8134 and% with% with 0x00ff8135 in> in my example, and with 1 byte of difference since the variables are allocated as x1
):
Dai,ifyoureadtox2
before,youcanseethatthefunctionchanges4bytes(Icompiledto32bits).
Beforechar
inx2
:
After scanf
in x2
(with input scanf
):
Thesamewillbetrueforreadingtox2
youdonext,exceptthat,sincethememoryisupdatedin4bytes,theoriginalvalueof7
willbechanged,thestartaddressinthefollowingscreensisthatofthex1
variable,butitisnolongerthesameasbeforebecauseIcapturedthescreensinanewrun).
Beforereadingavalueforx2
(withinputofx1
,inmyexample):
After reading a value for x1
(notice how the memory area of 2
has changed):
Thisiswhythex1
functionisconsideredunsafeanditsuseisnotrecommended.Torunmytest,forexample,Ihadtouse:
#define_CRT_SECURE_NO_WARNINGS
Withoutthisdefine,thecompileritself(inmycase,VisualStudio2012)advisesusing a Microsoft alternative called x2
.