[英]Segmentation Fault Issues in Game of Life Implementation
對於並行計算課程中的項目,我需要實現生命游戲的並行版本。
我使用的是我的教科書作者編寫的函數“ read_row_stripped_matrix”。 該函數從一個文件中讀取輸入,該文件包含矩陣中的行數,矩陣中的列數以及矩陣中的數據。
該函數通過分配一個稱為“存儲”的一維數組來建立二維矩陣,該數組保存矩陣的所有數據。 二維矩陣的每一行都指向其在存儲中的第一個元素,如下圖所示:
我們需要清理功能代碼,使其適合我們的C風格指南。 因此,我整理了一些內容,以使其更具可讀性。
現在,我遇到的問題是將矩陣中的每一行指向存儲中的第一個元素。 連接這些指針時出現分段錯誤,特別是在函數的這一部分:
/* Dynamically allocate matrix. Allow double subscripting
through 'a'. */
*storage = my_malloc (id, local_rows * *n * sizeof(int));
*subs = my_malloc (id, local_rows * PTR_SIZE);
for (i = 0; i < local_rows; i++) {
*subs[i]=&(*storage[i * *n]);
}
讓我感到困惑的是,我很確定自己已經為陣列分配了足夠的內存。 在示例中,我正在測試* m和* n等於5,local_rows等於5。因此,我為存儲分配了25 * sizeof(int),足以容納5x5矩陣的所有元素。
這是my_malloc函數,它為特定處理器分配內存:
/*
* Function 'my_malloc' is called when a process wants
* to allocate some space from the heap. If the memory
* allocation fails, the process prints an error message
* and then aborts execution of the program.
*/
void* my_malloc (
int id, /* IN - Process rank */
int bytes) /* IN - Bytes to allocate */
{
void *buffer;
if ((buffer = malloc ((size_t) bytes)) == NULL) {
printf ("Error: Malloc failed for process %d\n", id);
fflush (stdout);
MPI_Abort (MPI_COMM_WORLD, MALLOC_ERROR);
}
return buffer;
}
老實說,我發現指針令人困惑,如果問題很明顯,請原諒我。 我從事這項工作的時間超過了我應有的時間,因此我的大腦可能被炸了。
如果您需要更多代碼,請隨時詢問。
首先,您執行以下操作:
*subs = my_malloc (id, local_rows * PTR_SIZE);
然后,您執行以下操作:
*subs[i]=&(*storage[i * *n]);
很確定那是您的問題,就在那里。 在我看來,它確實應該是:
(*subs)[i]=&(*storage[i * *n]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.