Scanf function changes value of in-loop variable

Dicebot public at dicebot.lv
Wed Apr 16 11:08:23 PDT 2014


On Wednesday, 16 April 2014 at 17:47:05 UTC, Capture_A_Lag wrote:
> Hi all!
> I have this code:
>
> ------------------------------------------------------------------------------
> ubyte N, M, K;
> ubyte[][max][max] Matrix;
>
> scanf("%d %d %d", &N, &M, &K);
>
> ubyte tmp;
>
> for(ubyte n = 1; n <= N; n++)
> 	for(ubyte m = 1; m <= M; m++)
> 	{
> 		scanf("%d", &tmp);
>                 // After this scanf n becomes 0 for no reason
> 		
>                 if(tmp) Matrix[m][tmp] ~= n;
>         }
>
> ------------------------------------------------------------------------------
>
> After scanf in loop variable n becomes 0. Is this a bug? Please 
> help me!

scanf is inherently unsafe routine and does not protect you from 
type mismatch. In your snipper "%d" implies that argument is 
address of integer variable, however you supply it address of 
ubyte one. As loop variable happens to be on stack right next to 
`tmp` variable, it gets stomped when sizeof(int) bytes get 
written to &tmp


More information about the Digitalmars-d-learn mailing list