Search code examples
cmacossegmentation-faultbubble-sort

I tried to compile and run the following bubble sort program using the gcc but it shows the error


{

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.


Solution

  • 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;
    }