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
asked Sep 15, 2013 at 17:01
4
  • It is not only C, it is C and Linux (or at least Posix!). So please add more tags... Commented Sep 15, 2013 at 17:03
  • 1
    *details is defined, but *details->info is not. Commented 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. Commented 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". Commented 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).

answered Sep 15, 2013 at 17:05
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.