Targeting failure: Image of the recorded core

0

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 gives the following message:

  

Targeting failure (recorded core image)

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;
}
    
asked by anonymous 05.08.2018 / 02:19

2 answers

2

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

What I probably wanted was to declare the vector after asking how many positions it would be (as I did in the code), then you store in memory the space for the quantity entered, stop picking up an arbitrary value.

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

This error probably has to do with the craze people want to teach C as it was in the 1970s, or as it is in Pascal. That's why I'm critical of almost all the programming courses out there, they do not teach you how to program in real.

The code still does not take some care, but exercise is good. I've improved the organization to be more readable and more efficient (a loop solves the issue, you do not have to ask for the data and then scan the entire array to find the information you want).

#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);
}
    
05.08.2018 / 02:30
1

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 function starts.

    
05.08.2018 / 02:44