Search code examples
carraysipcshared-memorydetach

How do you detach an array of strings from shared memory? C


I have:

int array_id;
char* records[10];

// get the shared segment
if ((array_id = shmget(IPC_PRIVATE, 1, 0666)) == -1) {
            perror("Array Creating");
}

// attach
records[0] = (char*) shmat(array_id, (void*)0, 0);
if ((int) *records == -1) {
     perror("Array Attachment");
}

which works fine, but when i try and detach i get an "invalid argument" error.

// detach
int error;
if( (error = shmdt((void*) records[0])) == -1) {
      perror(array detachment);   
}

any ideas? thank you


Solution

  • In shmdt(), no need to convert the pointer argument to void* it will automatically take care of this .

    Remove (void*) from shmdt((void*) records[0])). It should be like this.

    if ((error = shmdt(records[0]) ) == -1)
    {
      perror("Array detachment");
    }
    

    And it will work.

    Also in shmat() , on error it returns (void*) -1 so your comparison will give warning. so do like this

    if ((char *)records[0] == (void *)-1)
    {
      perror("Array Attachment");
    }