c - 访问共享内存段时出现段错误

标签 c segmentation-fault shared-memory

我需要实现一个在不同进程之间共享信息的程序。

但是当我尝试访问共享结构的成员时,会产生段错误。

我该如何解决?请在下面查看我的代码。

源文件:

#include <string.h>
#include <stdio.h>
#include "ShM.h"

#define SHM_SIZE 1024 

int main(){

    stablishMemory();
    Deck *deck = obtainMemory();
    strncpy(deck->cards,"carlos",SHM_SIZE);
    unlinkMemory();
    return 0;
}

头文件 (ShM.h):

#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include <unistd.h>

int idMemory;

typedef struct {
    char *cards;
}Deck;

Deck* letra;
#define SHM_SIZE 1024 

void stablishMemory(){
    idMemory = shmget (obtainkey(), SHM_SIZE, 0777| IPC_CREAT);
    letra = (Deck* )shmat (idMemory, NULL,0);
}

key_t obtainkey(){
    return ftok("/bin/ls",24);
}

void unlinkMemory(){
    shmdt((Deck*)letra);

}

Deck* obtainMemory(){
    return letra;
}

void destroyMemory(){
    shmctl(idMemory, IPC_RMID, (struct shmid_ds*)NULL);
    unlink(" ");
}

最佳答案

这个结构不是独立的。该结构可能在共享内存中,但指针 cards 可以指向任何地方。

typedef struct {
    char *cards;  // the memory that cards points to could be outside the segment
} Deck;

您必须分配卡片(它是一个悬挂指针),但更重要的是,您还必须从共享区域分配卡片,或者使其成为一个内联缓冲区(在结构内),例如:

要么:

deck = allocSharedMem(sizeof(*deck));
deck->cards = allocSharedMem(52);

或使其内联:

typedef struct {
    char cards[52];
} Deck;

关于c - 访问共享内存段时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564854/

相关文章:

c - 如何使用纹理单元(它们似乎不起作用)

c - 使用 fscanf 读取文件后无限循环

c - 进程 ID 的数学表达式作为网格大小、进程数量和线路 ID 的函数

c - 打开时出现段错误

c++ - Linux共享内存只允许读访问

c - 访问共享内存段的进程返回不同的值

c++ - 从共享内存存储和访问结构数组

c - 套接字编程: sending and receiving different data to different clients in C

c++ - 将 vector<string> 转换为 char** 会导致段错误

c++ - SEGFAULT 使用 MySQL/C++ 连接器获取结果