0
我正在使用共享內存的項目,現在正在做一個令人難以置信的seg故障。出於某種原因,並非所有分配給*節點的內存都可訪問。在某個索引處(程序的每次運行都相同),內存無法寫入。下面是我的代碼和一些輸出。C共享內存段錯誤
int shf = shm_open("/queue", O_RDWR|O_CREAT, 0666);
int success = ftruncate(shf, sizeof(QNode)*numVertices*numVertices);
QNode *node = (QNode*) mmap(NULL, sizeof(QNode)*numVertices*numVertices, PROT_READ|PROT_WRITE, MAP_SHARED, shf, 0);
int a, b;
for (a=0; a<numVertices; a++) {
for (b=0; b<numVertices; b++) {
(node[sizeof(QNode)*a*numVertices + sizeof(QNode)*b]).k = a;
(node[sizeof(QNode)*a*numVertices + sizeof(QNode)*b]).i = b;
printf("Mapping to offset %d\ti:%d\tk:%d\n", sizeof(QNode)*a*numVertices + sizeof(QNode)*b, (node[sizeof(QNode)*a*numVertices + sizeof(QNode)*b]).i,(node[sizeof(QNode)*a*numVertices + sizeof(QNode)*b]).k);
}
}
上較小的圖輸出:
// Bunch of output
Offset: 472 i:5 k:6
Offset: 480 i:6 k:6
Offset: 488 i:7 k:6
Offset: 496 i:8 k:6
Offset: 504 i:0 k:7
Offset: 512 i:1 k:1
Offset: 520 i:1 k:1
Offset: 528 i:1 k:0
Offset: 536 i:1 k:1
Offset: 544 i:1 k:1
Offset: 552 i:1 k:0
Offset: 560 i:0 k:0
// More incorrect output down here
在下面的較大圖的輸出,有一些我不能發佈這裏 - 偏移量7168更令人費解的結果時,其開始打印出非可打印字符。例如,在偏移量7168的行上,我看到Ma [NUL] [NUL] [NUL] [NUL] [SI] [NUL] [NUL] [NUL]偏移量7168 ...下面是我可以實際顯示的輸出更大的圖表 - 在最後一行之後它出現故障。在更大的圖形
輸出:
// Bunch of output
Mapping to offset 9136 i:54 k:17
Mapping to offset 9144 i:55 k:17
Mapping to offset 9152 i:56 k:17
Mapping to offset // This is where it seg faults...
任何幫助是極大的讚賞!