【问题标题】:C : shmget with a 2D arrayC:带有二维数组的 shmget
【发布时间】:2012-04-05 10:30:51
【问题描述】:

我尝试将 shmget 与 2D 数组一起使用。 这是我的代码:

char **array;
key_t key;
int size;
int shm_id;
int i = 0;
void *addr;

key = // here I get the key with ftok()
size = (21 * sizeof(char *)) + (21 * sizeof(char **));
shm_id = // here I get the shmid with shmget()

if (shm_id == -1) // Creation
{
     array = (char **)shmat(shm_id, NULL, SHM_R | SHM_W);
     while (i != 20)
     {
         array[i] = memset(array[i], ' ', 20);
         array[i][20] = '\0';
         i++;
     }
     array[i] = NULL;
     shm_id = // here I get the shmid with the flag IPC_CREAT to create the shared memory
     addr = shmat(shm_id, NULL, SHM_R | SHM_W);
}

但是“array[i] = memset(array[i], ' ', 20);”这一行出现了分段错误

我做错了什么?

【问题讨论】:

    标签: c linux arrays unix shared-memory


    【解决方案1】:

    你应该首先检查 shmget 是否成功。如果共享内存分配失败,那么您就不能使用共享内存! ;-) 喜欢:

    If ( shm_id = shmget(.......) == -1) {
    exit(1);
    }
    else {
    /* proceed with your work*/
    }
    

    对于 shmat 也是如此。

    shmget 返回 void*。您不能将其分配给 char** 并像二维数组一样使用它。事实上,一个 char* 可以很容易地在逻辑上作为二维数组处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2012-11-15
      • 2012-05-14
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多