c - 为什么我的共享内存中的链表总是导致段错误?

标签 c linked-list shared-memory

我有以下简单的应用程序。这已经被剥夺了错误处理等,这是一个最小的完整示例。

#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;
}

关于c - 为什么我的共享内存中的链表总是导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38780416/

相关文章:

c - C 中使用共享内存的 IPC

c - strtok 删除除第一个标记之外的字符串

c - 使用链接列表添加和减去 Bigint

c++ - 链接堆栈中的唯一指针

c++ - 想要有效地克服 Boost.Interprocess 共享内存中映射中关键类型之间的不匹配

谁能帮我用C语言创建一个共享内存段

无法让 C 中的 while 函数工作

c - SDL测量文本

c - 不使用 printf 打印新行

c - 如何设置指针无效?