-2

I just encountered a malloc trouble in my assignment //This is my header file

struct vertex_t {
    int id;
    char *label;

    /* A list of vertices representing incoming edges */
    List in;
    /* A List of vertices representing outgoing edges */
    List out;
};
struct graph_t {
    /* Number of vertices */
    int order;
    /* Numb er of edges */
    int size;
    Vertex vertices;
};

//We are not allowed to change the header file above. In my main file, how can i malloc the vertices in the graph?

Graph new_graph(int order) {
    Graph graph;
    int i;
    graph=NULL;
    graph=(Graph)malloc(sizeof(Graph));
    assert(graph);
    graph->order=order;
    graph->size=0;
    graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));//!!!!!!!!!!!!!!!!!!!this line!!!!
    for(i=0;i<order;i++){
        graph->vertices[i].label=(char*)malloc(MAX_LINE_LEN*sizeof(char));
        graph->vertices[i].in=NULL;
        graph->vertices[i].out=NULL;
    }
    return graph;
}

I only can add the extreme large number in the malloc to prevent memory leak.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100

2 Answers2

1

It's hard to see all errors as you don't give a complete program, but as far as I see you made an error with this lines:

graph=(Graph)malloc(sizeof(Graph));
graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));

Graph and Vertex seems to be a pointer type, so you should do this instead:

graph = malloc(sizeof(struct graph_t));
graph->vertices = malloc((order)*sizeof(struct vertex_t));

I assume Vertex is the pointer type associated to struct vertex_t and Graph is the pointer type associated to struct graph_tin your headers.

We don't use malloc() to allocate memory for the pointer itself but for the data it is pointing. So the size depends on the data. If pType is a pointer type such as char *, int * or struct my_struct *, sizeof(pType) will allways be the same (8 for a 32-bit program or 16 for a 64-bit program for instance).

jdarthenay
  • 3,062
  • 1
  • 15
  • 20
0
 Graph graph;
 graph = (Graph)malloc(sizeof(Graph));

This is the first problem. Observe correct patterns:

struct Foo { ... };

Foo* foo = malloc(sizeof(Foo)); // one way
foo = malloc(sizeof(*foo)); // the other way, handy when you are not sure what your type is

Note how you pass in the size of the struct and get back a pointer.

Same thing happens with the second allocation:

graph->vertices = (Vertex*)malloc((order+100000)*sizeof(Vertex));

In your code both Graph and Vertex are pointers, but you want to allocate pointed-to structures, not pointers.

In addition, you cast the result to Vertex* but assign it to Vertex. This should have provoked a compiler warning. You must read, understand and eliminate all warnings, no exception. I recommend setting up your compiler so that it treats warnings as errors.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243