Question

I'm writing a program that reads from a text file and try to create a structure dynamically.

So I have the following code to do that:

typedef struct tgraph {
    int vertex_count;
    int edge_count;
    struct tvertex **adj;
} Graph;

typedef struct tvertex {
    int n; /* vertex number */
    char course[255];
    struct tvertex *next;
} Vertex;

Graph g_graph;

void create_graph(FILE *fd) 
{
    int vertex_count;
    int edge_count; 
    fscanf(fd, "%i", &vertex_count);
    fscanf(fd, "%i", &edge_count);
    printf("Vertices: %i\n", vertex_count);
    printf("Edges: %i\n", edge_count);
    g_graph.vertex_count = vertex_count;
    g_graph.edge_count = edge_count;
    g_graph.adj = malloc(sizeof(Vertex *));
    Vertex **vlist = g_graph.adj;
    int i;
    for (i = 0; i < vertex_count; i++) {
        Vertex *vertex = malloc(sizeof(Vertex));
        fscanf(fd, "%i,%[^\n]", &vertex->n, vertex->course);
        printf("%i %s\n", vertex->n, vertex->course);
        *vlist = vertex;
        vlist ++;;
    }
}

I'm calling this function create_graph and getting this error at runtime

corrupted double-linked list: 0x00000000007d7240

This is caused in the main function by a call to fclose(fd). I know that the problem is that I am corrupting the heap. My pointer arithmetic is probably wrong but I'm not able to solve it.

I'm compiling with gcc at linux.

Was it helpful?

Solution

The line g_graph.adj = malloc(sizeof(Vertex *)) only allocates space for one Vertex pointer. As soon as you do vlist++, you move into unallocated space, and any use of that space is undefined.

You'll need to change that first malloc call to malloc(sizeof(Vertex *) * vertex_count) to properly allocate the space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top