【问题标题】:Creating a 2D array of char in the shared memory c在共享内存 c 中创建 char 的 2D 数组
【发布时间】: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(...) reassigns shm,使您丢失早期的分配并给您带来内存泄漏。
  • 所以如果我在shmat(...) 之后分配,我的shm 还会在我的共享内存中吗?
  • 更重要的是,shm =(char**)shmat(...) 设置shm 指向一些已经被另一个进程存储的指针。这些指针在其他进程的地址空间中有地址。它们通常在此进程的地址空间中无效。
  • 另外,当你问这样的问题时,你应该提供一个minimal reproducible example,包括两个程序的完整源代码,可以编译和运行来演示问题。

标签: c arrays shared-memory double-pointer


【解决方案1】:

问题在于shmjagged array,而不是共享内存所需的连续内存区域。

在内存中shm 看起来像

+--------+ +-----+ | shm[0] | --> | ... | +--------+ +-----+ | shm[1] | --> | ... | +--------+ +-----+ | shm[2] | --> | ... | +--------+ +-----+ | ... | +--------+

shm的每个元素都是一个指针

对于一个“正确的”二维数组,每个元素都需要是一个数组

+-----------+------------+------------+-----+ | shm[0][0] | shm[0][1] | shm[0][2] | ... | +-----------+------------+------------+-----+ | shm[1][0] | shm[1][1] | shm[1][2] | ... | +-----------+------------+------------+-----+ | shm[2][0] | shm[2][1] | shm[2][2] | ... | +-----------+------------+------------+-----+ | ... | +-----------+------------+------------+-----+

作为一个简单的解决方案,您可以使用一种算法将shmat 返回的连续区域视为模拟二维数组:

char *shm;

// ...

for (j=0;j<30;j++)
    strcpy(&shm[j * 100], "I'm here");

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多