1

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
4
  • It is not only C, it is C and Linux (or at least Posix!). So please add more tags... Sep 15, 2013 at 17:03
  • 1
    *details is defined, but *details->info is not.
    – Dave
    Sep 15, 2013 at 17:05
  • 1
    Dave is right. The problem is that you have not allocated space for details->info so the next dereference ->id fails. This has nothing to do with shared memory.
    – UncleO
    Sep 15, 2013 at 17:10
  • UncleO: Not necessarily so. It's shared memory, so that it need not be initialized in this process. OP already stated "My process is accessing a shared memory that is already created". Sep 16, 2013 at 14:15

2 Answers 2

5

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).

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.