简体   繁体   English

C结构中的内存错误

[英]C Memory error in structs

The following code snippet causes a memory error for big MAXV values. 以下代码段会导致MAXV值较大的内存错误。 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;
}

Reading from my crystal ball, I see that you are creating local variables of type graph . 从我的水晶球中读取,我看到你正在创建类型graph局部变量。 Each of these local variables are in excess of 10,000,000 bytes large, which overflows the available stack space in your system. 每个局部变量都超过10,000,000字节,这会溢出系统中可用的堆栈空间。

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

Either use dynamic allocation or increase stack size (asserting linux-like OS) by executing: 通过执行以下命令来使用动态分配或增加堆栈大小(断言类似Linux的操作系统):

ulimit -s 1000000 ulimit -s 1000000

size would be in kB thus max allowed stack size would be ~100MB. 大小将以kB为单位,因此最大允许堆栈大小约为100MB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM