【问题标题】:Getting value from dynamically allocated 2D array从动态分配的二维数组中获取值
【发布时间】:2018-09-25 09:49:41
【问题描述】:

我是 C 编程的新手,所以我可能在这里做了一些非常愚蠢的事情。我正在尝试从我从文本文件中读取的 2D 数组中获取值 ~70m 行。

运行代码时,出现段错误,我已将其缩小到第 10 行: if (i == graph[j][0])

void convertToCSR(int source, int maxNodes, int maxEdges, int* vertices, int* edges, int** graph) {
int i;
int j;
int edge = 0;

for (i = 0; i < maxNodes; i++) {
    vertices[i] = edge;

    for (j = 0; j < maxEdges; j++) {
        if (i == graph[j][0]) {
           //Sets edges[0] to the first position
            edges[edge] = graph[j][1];
            printf("new edge value: %d\n", edge);
           edge++;
         }
    }
}
vertices[maxNodes] = maxEdges;}

我已经尝试过使用较小的数据集(例如 50 字节)并且效果很好。通过进一步测试,我打印出 graph[0][0] 的值,我得到一个段错误。

图表已加载数据并分配如下:

int num_rows = 69000000;
graph = (int**) malloc(sizeof(int*) * num_rows);
for(i=0; i < num_rows; i++){
    graph[i] = (int*) malloc(sizeof(int) * 2 );
}

我也可以在此方法之外获取 graph[0][0] 的值,但不能在内部获取。我做错了什么?感谢您的帮助。

编辑:在我的主要方法中,我正在执行以下操作:

readInputFile(file);
int source = graph[0][0];
convertToCSR(source, maxNodes, maxEdges, nodes, edges, graph);

我有正确的变量值:源。 它在 convertToCSR 方法中分段错误。

【问题讨论】:

  • 并且您的系统有至少 264 MiB(在 32 位系统上,在 64 位系统上翻倍)您要为 graph 分配的内存所需的连续可用内存?没有malloc 调用返回空指针?
  • 在我的主要方法中,我能够在填充图表后获取值。但是当我调用这个方法时,它会出现错误
  • 为什么不检查malloc() 返回值。运行gdb 并执行bt 它说什么?
  • 仅仅因为它似乎工作并不意味着它实际上工作。这是undefined behavior 的问题之一(您可能在某个地方遇到过)。
  • 我得到了 x86_64 上所需的 1104000000 字节(69000000 *(每个指针 8 字节 + 2 int 8 字节))。仅分配的存储空间就是 1.1G - 可行,但很大。这并没有解决任何额外的读取内存问题。您需要验证每个分配以确保malloc 不会失败。

标签: c pointers graph-theory dynamic-allocation


【解决方案1】:

您正在使用 num_rows 存储大于 int 容量的数字。

所以实际值 int num_rows 不是 69000000,因为溢出。

尝试改用long unsigned int num_rows

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2012-09-20
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多