【问题标题】:Confusing Segmentation Fault When Reading From File从文件读取时令人困惑的分段错误
【发布时间】:2019-04-15 19:30:01
【问题描述】:

所以,我正在尝试将整数文件读入 2 个单独的矩阵。第一个矩阵可以很好地读取。然后第二个尝试从文件中读取,到达最后一行并到达段错误。我已经查看了无数次的代码,但无法弄清楚为什么会出现这个段错误。任何帮助都会有所帮助!

相关代码贴在下面:

int** allocation_matrix;
int** request_matrix;

allocation_matrix = (int **) malloc(num_processes * sizeof(int));
request_matrix    = (int **) malloc(num_processes * sizeof(int));

for (i = 0; i < num_processes; i++)
{
    allocation_matrix[i] = (int *) malloc(num_resources * sizeof(int));
    request_matrix[i]    = (int *) malloc(num_resources * sizeof(int));
}

for (i = 0; i < num_processes; i++)
{
    for (j = 0; j < num_resources; j++)
    {
        fscanf(fp, "%d", &allocation_matrix[i][j]);
    }
}

for (i = 0; i < num_processes; i++)
{
    for (j = 0; j < num_resources; j++)
    {
        fscanf(fp, "%d", &request_matrix[i][j]);
        printf("%d ", request_matrix[i][j]);
    }
    printf("\n");
}

【问题讨论】:

  • 分配大小错误num_processes * sizeof(int)。建议allocation_matrix = malloc(sizeof *allocation_matrix * num_processes);。不易出错。 (也是request_matrix)。也许还有其他问题。
  • 解决了我的问题!非常感谢:D 我不知道我能做到这一点,哈哈

标签: c file segmentation-fault


【解决方案1】:

num_processes * sizeof(int) 是错误的大小,因为使用了错误的类型。

不要尝试对指针使用正确的类型,而是根据取消引用的指针确定大小。更容易正确编码、审查和维护。

// allocation_matrix = (int **) malloc(num_processes * sizeof(int));
allocation_matrix = malloc(sizoef *allocation_matrix * num_processes);

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2016-07-04
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2012-09-12
    相关资源
    最近更新 更多