[英]Confusing Segmentation Fault When Reading From File
因此,我正在嘗試將整數文件讀入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 = (int **) malloc(num_processes * sizeof(int));
allocation_matrix = malloc(sizoef *allocation_matrix * num_processes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.