Array bug in size 4

3

I'm asking you the following question:

So I did this algorithm:

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

int main()
{
int i, j, x=0;
int vetor[x];       

printf ("Digite o tamanho do vetor:\n");
scanf ("%d", &x);

for (i=0; i<x; i++)
{
    printf ("\nDigite o numero de posicao %d do vetor:\n", i);
    scanf ("%d", &vetor[i]);
}

system("cls");

for (i=0; i<x; i++)
{
    for (j=i+1; j<x; j++)
    {
        if (vetor[i] == vetor[j])
            printf ("\nO numero %d se repete\n", vetor[i]);
            break;
    }
}
return 0;

}

But if I type the size of the vector (x) is equal to 5 or greater, when I enter the fifth number the program ends. Any idea how to solve the problem? I'm using Dev-C ++ 5.11

    
asked by anonymous 12.05.2018 / 23:51

1 answer

3

You have two subtle errors in the code:

  • int i, j, x=0;
    int vetor[x];      
    

    Note that vetor is created with 0 size because x is 0 at the time of its declaration, causing any access to vetor to result in undefined behavior. This can have all sorts of behaviors from a Segmentation Fault that seems to be what it indicated, or even an infinite loop of input numbers, which is what happened on my machine. This infinite loop is usually the sign of Buffer Overflow > writing about local variables. In case you just need to rewrite over i with the right value to make it infinite.

    The fix is to even change the location where you allocate, so that it is after reading x :

    int i, j, x;
    
    printf ("Digite o tamanho do vetor:\n");
    scanf ("%d", &x);
    int vetor[x]; // <--- agora aqui
    

    Note that I also removed the initialization of x=0 in the declaration because it is not necessary, since the first thing you do with x is to assign through scanf .

  • if (vetor[i] == vetor[j])
        printf ("\nO numero %d se repete\n", vetor[i]);
        break;
    

    Notice that here you have fooled yourself visually, indenting break as if it were within if but in fact is not, since if does not have {} . This is a very common error and sometimes difficult to see because the program does not make any mistake, simply behaves differently than we would expect. If you want to play by goal always {} even when you have only one instruction, so make sure you never fall into these traps.

    Just to make it clear, I'd fix it like this:

    if (vetor[i] == vetor[j]){
        printf ("\nO numero %d se repete\n", vetor[i]);
        break;
    }
    
  • View the code with these two fixes working on Ideone

        
    13.05.2018 / 01:45