在共享内存 c 中创建一个 char 的二维数组

Creating a 2D array of char in the shared memory c

我想创建一个 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;

}

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

在记忆中 shm 看起来像

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

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

对于 "proper" 二维数组,每个元素需要是一个 数组:

+-----------+-----------+-----------+-----+
| 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");