0

{

int *v;
int i=0; 
int n;
int j=0;
int aux=0;
File *fp;

fp = fopen("Inteiros.txt", "r"); /*opening a file and read it*/

if(fp == NULL)

    printf("Erro, ficheiro nao encontrado!\n");/*portuguese sentence*/

else

    while(!feof(fp))

    {
        fscanf(fp, "%d", &v[i]);
        i++;
    }

    for(i=1; i<n; i++)
    {   
        for(j=0; j< n-i-1; j++)
        {
            if(v[j] > v[j+1])
            {   
                aux = v[j];
                v[j] = v[j+1];
                v[j+1] = aux;
            }
        }   
    }

than gave me the "segmentation fault" error and I don't know why. I know its a piece of the memory that I don't have access, but I don't know where is the error.

1 Answers1

1

You're likely getting a seg fault because you didn't allocate any memory for you pointer int *v and then you try to assign values to it like it's an array. Also int n; was never initialized so your getting into undefined behavior. Also File is not a type unless you made your own that you're not showing, should be FILE.

Try something like this:

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

#define MAX_NUMS  1024

int main()
{

   int *v;
   int i=0, j=0, aux=0, n = 0;
   FILE *fp;

   fp = fopen("Inteiros.txt", "r");

   if(fp == NULL) {
      printf("Erro, ficheiro nao encontrado!\n");
      return 1;
   }
   else {
      //allocate memory for v
      if ((v = malloc(sizeof (int) * MAX_NUMS)) == NULL) {
         printf("Error in malloc\n"); 
         return 1;
      }

      while(!feof(fp)) {
         fscanf(fp, "%d", &v[i]);
         i++;
      }
      //number of lines read
      n = i;
      for(i = 0; i < n; i++) {
         for(j = 0; j < n-i-1; j++) {
            if(v[j] > v[j+1]) {
               aux = v[j];
               v[j] = v[j+1];
               v[j+1] = aux;
            }
         }
      }
      for (i = 0; i < MAX_NUMS; i++)
         printf("v[%d] is %d\n", i, v[i]);
   }
   return 0;
}
Tormund Giantsbane
  • 355
  • 1
  • 4
  • 12
  • problems with this answer: 1) this answer is still outputting error messages to `stdout` rather than `stderr` 2) still using `while( !feof(fp)` when it should be using the returned value from the call to `fscanf()` to control the loop. so not a very good answer – user3629249 May 12 '18 at 13:30
  • unless the number of data items read is `MAX_NUMS`, this loop: ` for (i = 0; i < MAX_NUMS; i++)` will be printing uninitialized garbage. – user3629249 May 12 '18 at 13:35
  • Regarding: `while(!feof(fp)) { fscanf(fp, "%d", &v[i]);` This loop fails to stop when MAX_NUMS numbers have been read, so can be setting values past the end of the allocated memory .. Which would result in undefined behavior. – user3629249 May 12 '18 at 13:38