Home > Blockchain >  Why this variable auto edit?
Why this variable auto edit?

Time:10-13

Contest : I have a vector and i need to shift it by left (dir=1) or right(dir=-1) so far a very simple thing, only in the for loop I don't know why but many times the dir variable is changed for i don't know what reason. Could someone please explain me why? Precisely it is changed by itself when the function returns.

#include <stdio.h>
#include <stdlib.h>
#define maxN 6
void ruota(int v[maxN],int N,int P,int dir)
{
    //rotazione a destra
    switch(dir){
        case -1:
        {
            for(int i=P;i<N;i  )
            {
                int mod=i%P;
                //scambio
                int tmp=v[mod];
                v[mod]=v[i];
                v[i]=tmp;
            }
            break;
        }
        case 1: //rotazione a sinistra
        {
            for(int i=N-P;i>=0;i--)
            { int mod=N-i%P;
                //scambio
                int tmp=v[mod];
                v[mod]=v[i];
                v[i]=tmp;
            }


        }
    }
}
int main()
{
    int pos;
    int dir=0;
    int vet[maxN];
    printf("Acquisizione vettore \n");
    for(int i=0;i<maxN;i  )
    {scanf("%d",&vet[i]);}
    printf("Posizione: \n");
    scanf("%d",&pos);
    printf("Direzione: \n");
    scanf("%d",&dir);
    for(;pos>0;pos--)
    {
        ruota(vet,maxN,1,dir);  //Why this function change dir variable?
    }
    //stampa
    for(int i=0;i<maxN;i  )
    {
        printf("%d ",vet[i]);
    }
    return 0;
}

CodePudding user response:

In the 'rotate left' branch you have

        for(int i=N-P;i>=0;i--)
        { 
            int mod=N-i%P;
            //scambio
            int tmp=v[mod];
            v[mod]=v[i];
            v[i]=tmp;
        }

With P == 1 as ruota() is called, i%P will always be 0 thus mod == N. So when you assign v[mod]=v[i] you have a buffer overflow which in your case overwrites dir

  •  Tags:  
  • c
  • Related