簡體   English   中英

為什么共享內存中的鏈表始終導致段錯誤?

[英]Why does my linked list in shared memory always lead to a segfault?

我有以下簡單的應用程序。 除去了錯誤處理,這是一個最小的完整示例。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

//#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

struct node
{
    int x;
    struct node *next;
};

int main(int argc, char *argv[])
{
    struct node *root[argc+1];
    if (argc > 1)
    {
        int i;
        root[0]=  (struct node *) malloc( sizeof(struct node) );
        for (i=0; i<argc-1; i++)
        {
            root[i]->x = (int)(*argv[i+1]-'0');
            //root[i]->next=&root[i]+sizeof(struct node);
            root[i+1]=(struct node *) malloc( sizeof(struct node) ); //Okay, wastes a few ops
            root[i]->next=root[i+1];
        }
        free(root[i]->next);
        root[i]=NULL;
    }

    key_t key;
    int shmid;
    struct node *data;

    key = ftok("test1", 'O');
    shmid = shmget(key, (size_t)(sizeof(struct node)*1000), 0777 | IPC_CREAT);


    data = shmat(shmid, (void *)0, 0);
    printf("%p", &data);

    if (argc != 1)
    {
        int z=0;
        for (z=0;z<argc-1;z++){
            *(data+sizeof(struct node)*z)=*root[z];
            if (z) (data+sizeof (struct node)*(z-1))->next=(data+sizeof (struct node)*z);
        }
        (data+z)->next=0;

    }

if (argc)
    {
        printf("This is the routine that will retrieve the linked list from shared memory when we are done.");
        struct node *pointer;
        pointer=data;
        printf("%p", data);

        while (pointer->next != 0)
        {
            printf("\n Data: %i",pointer->x);
            pointer=pointer->next;
        }
    }
    /* detach from the segment: */
    if (shmdt(data) == -1)
    {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

基本上,每當我嘗試從創建共享內存的進程訪問共享內存時,我的輸出看起來都很好。 每次我從未創建共享內存的進程(argc = 1)打開共享內存時,程序就會出現段錯誤。 如果有人能告訴我原因,我將不勝感激!

每次在進程中附加共享內存段時,它都會附加到某個地址,該地址與附加共享內存的任何其他進程中的地址無關。 因此,共享內存中的指針在指向原始(正在創建)進程的共享內存中的共享內存中的其他對象時,不會指向任何其他進程中的共享內存。

最終結果-如果您想將數據結構存儲在共享內存中,那么如果您希望它們合理工作,則這些數據結構不能包含任何指針。 如果您想要類似指針的行為,則需要使用共享內存中的索引(可能作為數組)。 因此,您可以執行以下操作:

struct node {
    int x;     /* value */
    int next;  /* index of the next node */
};


struct node *data = shmat(...);  /* shm was sized for 1000 nodes */

/* link all of the data objects into a linked list, starting from data[0] */
for (int i = 0; i < 1000; ++i) {
    data[i].next = i+1;
}
data[999].next = -1;  /* using -1 for "NULL" as 0 is a valid index; */

for (int i = 0; i >= 0; i = data[i].next) {
    /* iterating down the linked list */
    data[i].x = 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM