【发布时间】:2019-11-26 10:08:50
【问题描述】:
我想创建一个 char 的二维数组并通过共享内存共享它,但是当我尝试在我的共享内存中写入时出现分段错误,我该怎么做才能在我的数组中写入一个字符串
int main {
int j;
char** shm = malloc(30 * sizeof(char *));
for (int index=0;index<30;++index)
{
shm[index] =malloc(100 * sizeof(char));
}
int sh_id;
int i;
size_t sizeMatrix = sizeof_dm(30,100,sizeof(char));
//creation ou ouverture de la file de segment partag�e
key_t keyfile = ftok("keyFileIpc.txt",10);
if((sh_id = shmget(keyfile,sizeMatrix,IPC_CREAT|0666)) == -1) {
perror("shmget");
exit(1);
}
//on attache le segment au shm
if ((void*)(shm =(char**)shmat(sh_id, NULL, 0)) == (void *) -1) {
perror("shmat");
exit(1);
}
//i can't write in here and i don't know why
for (j=0;j<30;j++)
{
strcpy(shm[j],"i'm here");
}
printf("here\n");
return 0;
}
【问题讨论】:
-
shm =(char**)shmat(...)reassignsshm,使您丢失早期的分配并给您带来内存泄漏。 -
所以如果我在
shmat(...)之后分配,我的shm还会在我的共享内存中吗? -
更重要的是,
shm =(char**)shmat(...)设置shm指向一些已经被另一个进程存储的指针。这些指针在其他进程的地址空间中有地址。它们通常在此进程的地址空间中无效。 -
另外,当你问这样的问题时,你应该提供一个minimal reproducible example,包括两个程序的完整源代码,可以编译和运行来演示问题。
标签: c arrays shared-memory double-pointer