Home > Enterprise >  Segmentation fault memory allocation error
Segmentation fault memory allocation error

Time:05-10

I have a problem with my allocation in this program, I used Valgrind and the error I receive is:

Address 0xe9481f041af07000 is not stack'd, malloc'd or (recently) free'd

And when I compile I receive:

make: *** [Makefile:7: run] Segmentation fault (core dumped)

I am receiving errors in this part of my code, any ideas of what the problem could be?

#include <stdio.h>
#include <stdlib.h>
typedef struct 
{
    int left, right;
    int nr;
}intervals;
void read_alloc(int *n, intervals **v)
{
    int i;
    FILE *f = fopen("date.in", "r");
    fscanf(f,"%d", n);
    *v = (intervals *) malloc((*n) * sizeof(intervals));
    for (i = 0; i < *n; i  )
    {
       fscanf(f,"%d %d", &(v[i]->left), &(v[i]->right));
       v[i]->nr = i;
    }
    fclose(f);
}
int main()
{
    int n;
    intervals *v;
    read_alloc(&n, &v);
    for (int i = 0; i < n; i  )
    {
        printf("%d %d\n", v[i].left, v[i].right);
    }
    free(v);

return 0;

}

The input:

6
80 85
3 7
50 70
83 84
1 5
25 50

The compilation command:

gcc p1.c -Wall -g -o compiler

CodePudding user response:

you mix v and *v, you should not use v but *v

static void read_alloc(int *n, intervals **v)
{
    int i;
    FILE *f = fopen("date.in", "r");
    fscanf(f,"%d", n);
    *v = (intervals *) malloc((*n) * sizeof(intervals));
    for (i = 0; i < *n; i  )
    {
       fscanf(f,"%d %d", &((*v)[i].left), &((*v)[i].right));
       (*v)[i].nr = i;
    }
    fclose(f);
}

Using another variable can be easier, (and don't cast malloc)

static void read_alloc(int *n, intervals **_v)
{
    int i;
    intervals *v;
    FILE *f = fopen("date.in", "r");
    /* TODO check f */
    fscanf(f,"%d", n);
    v = malloc((*n) * sizeof(intervals));
    *_v = v;
    for (i = 0; i < *n; i  , v  ) {
         fscanf(f,"%d %d", &v->left, &v->right);
         v->nr = i;
    }
    
    fclose(f);
}
  • Related