Why does the order of these scanf's make a difference in the result?

3

The program adds x1 and x2 and places the result in x1 . It does not work if x1 is read before x2 . But if you reverse this order, it works.

#include <stdio.h>
#include <stdlib.h>

unsigned char x1,x2;

void soma() {
    x1 = x1 + x2;
}

int main()
{    
    /* Carga das variaveis que estao mapeadas na memoria */
    printf("Valor de x1 = "); scanf("%d", (int*)&x1);
    printf("Valor de x2 = "); scanf("%d", (int*)&x2);
//    printf("Valor de x1 = "); scanf("%d", (int*)&x1);

    soma();

    printf("x1=%d, x2=%d\n", x1, x2);
    return 0;
}
    
asked by anonymous 31.03.2015 / 18:02

2 answers

7

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,ifyoureadtox2before,youcanseethatthefunctionchanges4bytes(Icompiledto32bits).

Beforecharinx2:

After scanf in x2 (with input scanf ):

Thesamewillbetrueforreadingtox2youdonext,exceptthat,sincethememoryisupdatedin4bytes,theoriginalvalueof7willbechanged,thestartaddressinthefollowingscreensisthatofthex1variable,butitisnolongerthesameasbeforebecauseIcapturedthescreensinanewrun).

Beforereadingavalueforx2(withinputofx1,inmyexample):

After reading a value for x1 (notice how the memory area of 2 has changed):

Thisiswhythex1functionisconsideredunsafeanditsuseisnotrecommended.Torunmytest,forexample,Ihadtouse:

#define_CRT_SECURE_NO_WARNINGS

Withoutthisdefine,thecompileritself(inmycase,VisualStudio2012)advisesusing a Microsoft alternative called x2 .

    
31.03.2015 / 18:19
6

scanf("%d",...) will read and put an integer value (example 4 bytes) at the address passed to it.

Because the variable you are reading to has only one byte (char), the neighbor variable is run over. This kind of things can cause unpredictable effects (eg, segmentation fault)

    
31.03.2015 / 18:16