Array bug when passing size 4

Asked

Viewed 89 times

3

I’m asking a question that asks the following: Questão

So I made 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 that the vector size (x) is equal to 5 or greater, when I enter the fifth number the program finishes. Any idea how to fix the problem? I’m using Dev-C++ 5.11

  • For me it worked right in Code::Blocks.

1 answer

3


There are two subtle errors in the code:

  1. int i, j, x=0;
    int vetor[x];      
    

    Notice that vetor is created with size 0 for the x is 0 at the time of its declaration, causing any access to vetor results in undefined behavior. This can have all kinds of behaviors from a Segmentation Fault which appears to be what you indicated, or even an infinite loop of input numbers, which is what happened on my machine. This infinite loop is the general sign of Buffer Overflow writing about local variables. For the case just rewrite over the i with the right value to make infinite.

    The fix is even change the location where you allocate, so 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 statement as it is not necessary, since the first thing it does with x is to assign through the scanf.

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

    Notice that here you have fooled yourself visually by indenting the break as if inside the if but it really isn’t, because the if has not {}. This is a very common mistake and sometimes difficult to see because the program does not give any error, simply behaves differently than we would expect. If you want to play it safe always meta {} even when there’s only one instruction, so make sure I never fell for those traps.

    Just to be clear, I would correct:

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

See the code with these two fixes working on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.