Segmentation Fault (core dumped): array reading

3

I have a problem with reading an array that produces the error

  

Segmentation Fault (core dumped)

This is just the beginning of code development, but it already has an error after reading the first element of array .

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



void LerArray( int numElementos , float * elemArray ){

  int i;

  float num ;

  for( i = 0 ; i < numElementos ; i++ ){

      printf("Digite um numero para seu array:  ");

      scanf("%f", num );

      *( elemArray + i ) = num ;

      printf("/n/n");


  }


}


int main (){

  int numElementos;

  printf("Oi !!!  Quantos elementos vc quer armazenar :  ");

  scanf("%d", &numElementos );

  system("clear");

  float * vetorNum ;

  vetorNum = ( float * ) malloc( numElementos );

  LerArray( numElementos , vetorNum );

  return 0 ;

}
    
asked by anonymous 22.03.2015 / 14:55

2 answers

2

You have to multiply the number of elements by the size of each

vetorNum = malloc(numElementos * sizeof *vetorNum);

and check for memory allocation error

if (vetorNum == NULL) /* erro de alocação */;

And, when you no longer need memory, free up resources

free(vetorNum);
    
22.03.2015 / 15:03
2

The main thing that is causing this problem is that you are not allocating the amount of bytes you need for your vector.

The malloc() function stores bytes and not a number of elements , then you would need to multiply by the size of the data type of each element.

I also found a problem in scanf() that was not passing the argument by reference as it should be. And the line-jumping character was also wrong.

Otherwise, you are not releasing memory with free() . It does not cause a problem in this specific case because the program is very small, but it is customary to do this always so as not to create addictions.

Nothing guarantees that the allocation worked out, it would be interesting to check this out.

So I made these changes and the code looks like this:

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

void LerArray(int numElementos , float * elemArray) {
  int i;
  float num;

  for(i = 0; i < numElementos; i++) {
      printf("Digite um numero para seu array:  ");
      scanf("%f", &num);
      *(elemArray + i) = num;
      printf("\n\n");
  }
}

int main() {
  int numElementos;
  printf("Oi !!!  Quantos elementos vc quer armazenar: ");
  scanf("%d", &numElementos);
  system("clear");
  float * vetorNum;
  vetorNum = malloc(numElementos * sizeof(float));
  if (vetorNum == NULL) {
    printf("Erro na alocação, talvez funcione um um número de elementos menor ");
    return 0;
  }
  LerArray(numElementos, vetorNum);
  free(vetorNum);
  return 0;
}

See running on ideone .

    
22.03.2015 / 15:04