Segmentation fault 内存分配错误

Segmentation fault memory allocation error

我在这个程序中的分配有问题,我使用了 Valgrind,我收到的错误是:

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

编译时收到:

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

我在我的这部分代码中收到错误,您知道问题出在哪里吗?

#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;

}

输入:

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

编译命令:

gcc p1.c -Wall -g -o compiler

你混合使用 v*v,你不应该使用 v 而应该使用 *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);
}

使用另一个变量会更容易,(不要强制转换 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);
}