0

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;
}
6
  • What are the problems you have compile-time errors? run-time error? Commented Mar 7, 2012 at 19:43
  • 2
    That snippet can't cause a memory error, it only creates a type, not any variables. Please provide a complete minimal program that demonstrates the error you are having. sscce.org Commented Mar 7, 2012 at 19:44
  • What memory error does it produce? This program can't cause a compile time error. It may cause a run-time error if you don't have enough memory. Commented Mar 7, 2012 at 19:44
  • What kind of memory errors? Are you allocating on the stack or the heap? Commented Mar 7, 2012 at 19:44
  • I added the way I'm allocating it Commented Mar 7, 2012 at 19:59

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.