我需要实现一个在不同进程之间共享信息的程序。
但是当我尝试访问共享结构的成员时,会产生段错误。
我该如何解决?请在下面查看我的代码。
源文件:
#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/