尝试将堆上的变量复制到C中的共享内存时,Memcpy失败

时间:2014-04-17 00:37:34

标签: c posix shared-memory memcpy

我试图将一个struct I malloc复制并在堆上初始化为共享内存,以便我可以在我想要分叉的子进程中使用该结构。但是,当我进入memcpy时,我得到的错误是我尝试复制结构的地址是无效的地址。我不确定我搞砸了。

struct OverSharedData{
//pointers to other variables and structs
}

int main(){
struct OverSharedData* remp = (struct OverSharedData*)malloc(sizeof(struct OverSharedData));
initialize(remp);

key_t key = ftok("garbage.txt", 71);
int eyedee = shmget(key, sizeof(struct OverSharedData), IPC_CREAT);
struct OverSharedData* add = (struct OverSharedData *)shmat(eyedee, 0, 0);

memcpy(add, remp, sizeof(struct OverSharedData));
}

编辑:通过gdb返回值:

261 struct OverSharedData * add =(struct OverSharedData *)shmat(eyedee,0,0);

打印添加 $ 5 =(struct OverSharedData *)0x8fe005ec (gdb)接下来 263 memcpy(add,remp,sizeof(struct OverSharedData)); (gdb)print add $ 6 =(struct OverSharedData *)0xffffffff

1 个答案:

答案 0 :(得分:2)

很奇怪,我今天早些时候遇到了同样的事情。

shmget添加权限:

int eyedee = shmget(key, sizeof(struct OverSharedData), 
                   IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (eyedee == -1)
{
    perror("shmget");
    exit(1);
}

检查shmat的返回代码。

struct OverSharedData *add = (struct OverSharedData *) shmat(eyedee, 0, 0);
if (add == (void *) -1)
{
    perror("shmat");
    exit(1);
}