Angus
Angus

Reputation: 12621

Shared memory in C

My process is accessing a shared memory that is already created. The pointer attached to the shared memory is a structure containing a pointer and 2 or 3 variables.

eg:

typedef struct _info_t{
    int id;
    char c;
}info_t;

typedef struct _details_t{
    int buff_id;
    info_t* info;
}details_t;

details_t* details = shmat(shmid,(void*)0,0);
printf("\n %d \n",details->info->id);            // gives me a segmentation fault

Upvotes: 1

Views: 212

Answers (2)

shmat(2) is a syscall (on Linux). It may fail. So at least code

details_t* details = shmat(shmid,(void*)0,0);
if (!details) { perror("shmat"); exit(EXIT_FAILURE); };  

and you cannot put (easily) pointers in shared memory, since the address is specific to each process.

Upvotes: 1

If a memory segment is shared between more than one process, there's no guarantee it will be mapped at the same address, so you cannot store pointers in shared memory segment. Try to avoid using pointers, use offsets or arrays (if possible).

Upvotes: 5

Related Questions