Segmentation failure: Core Image recorded

I made a code in C to find the smallest value and position of it in a vector x [N]. Every time I compile the program through the terminal (Linux), it accuses the following message:

Segmentation failure (core image recorded)

I used the same code in Windows and the program ran successfully.

#include <stdio.h>

int main(){
int N, i, menor, posicao,  x[N];

scanf("%d",&N);

i=0;

for(i;i<N;i++) scanf("%d",&x[i]);

menor = x[0];
posicao = 0;

for(i;i<N;i++){ 
    if(menor > x[i]){
        menor = x[i];
        posicao = i;
    } 
}   
printf("Menor valor: %d", menor);
printf("Posicao: %d", posicao);

return 0;
}
Author: Maniero, 2018-08-05

2 answers

The main reason is that you are creating a vector with a random amount of positions, it is what is in the memory at that time, and this will cause the memory to burst most of the time, but not all.

What I probably wanted is to declare the vector after asking how many positions would be (as I did in the code), then you reserve in memory the space for the amount typed, stop taking an arbitrary value.

Has nothing to do with the operating system but with the memory garbage you have at that time of execution in the place that was allocated to your your application. It can eventually even repeat the same value, but it's just coincidence.

This mistake probably has to do with the craze people want to teach C as it was in the 70s, or as it is in Pascal. That's why I'm critical of almost every programming course out there, they don't teach how to program in real.

The code does not yet take some care, but for exercise it is good. I gave an improvement in the organization to become more readable and more efficient (a loop solves the issue, does not need to ask for the data and then scan the entire vector to find the desired information).

#include <stdio.h>
#include <limits.h>

int main() {
    int n;
    scanf("%d", &n);
    int x[n];
    int menor = INT_MAX;
    int posicao = 0;
    for (int i = 0; i < n; i++) { 
        scanf("%d", &x[i]);
        if (x[i] < menor) {
            menor = x[i];
            posicao = i;
        } 
    }   
    printf("Menor valor: %d Posicao: %d", menor, posicao);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

 2
Author: Maniero, 2020-07-28 15:10:48

Short answer: you are using N to create the array x [N] before the value of N is set, so it is random (but in general it will be zero).

Declare x [N] after scanf (). In C99 it is allowed to declare variables after the start of the function.

 1
Author: epx, 2018-08-05 00:44:30