ItsameMario
ItsameMario

Reputation: 121

C Memory error in structs

The following code snippet causes a memory error for big MAXV values. How can I define this struct that I can use it for many values in edges and degree?

#define MAXV  1441295   
typedef struct {
    edgenode *edges[MAXV+1];           
    int degree[MAXV+1];     
    int nvertices;      
    int nedges;         
    int directed;       
} graph;


initialize_graph(graph *g, bool directed)
{
    int i;              

    g -> nvertices = 0;
    g -> nedges = 0;
    g -> directed = directed;

    for (i=1; i<=MAXV; i++) g->degree[i] = 0;
    for (i=1; i<=MAXV; i++) g->edges[i] = NULL;
}

Upvotes: 0

Views: 106

Answers (2)

Tomas Pruzina
Tomas Pruzina

Reputation: 8887

Either use dynamic allocation or increase stack size (asserting linux-like OS) by executing:

ulimit -s 1000000

size would be in kB thus max allowed stack size would be ~100MB.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

Reading from my crystal ball, I see that you are creating local variables of type graph. Each of these local variables are in excess of 10,000,000 bytes large, which overflows the available stack space in your system.

Try creating the objects either as static objects or heap-allocated objects.

That is, don't do this:

int f(graph g) {
   graph newg = g;
}

Rather, do this:

graph g;
int f() {
  g.ediges[g.nedges++] = 0;
}

or this:

int f(graph *pg) {
  pg->edges[17] = 0;
}

Upvotes: 1

Related Questions