0
votes

As I am writing a school project in c and I am having trouble with using shared memory. For some reason my solution worked once and now it doesn't (very unscientific, I know).

I create a shared variable:

int *sharedVar = mmap(NULL, sizeof(int)*7, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);

And when I try to use it like this:

sharedVar[0]=1;

or this:

sharedVar[4]=0;

I get a Segmentation Violation (SIGSEGV) error message. I will be happy for any of your suggestions.

EDIT: strerror says:

Bad file descriptor

What does that mean?

SOLUTION: I haven't cleaned my memory. I feel stupid.

1
You must check the return value of mmap. That system call can fail. Check the return value and then errno (see the man page). - Mat
How do I do that exactly? - user3473750
Bad file desciptor...something is going on with shm_fd. - Duck

1 Answers

-1
votes

If I had to guess, I'd say you are not cleaning up your shared memory. Is this a unix system? Use the ipcs command to show all the shared memory. If you set up the shm once, and then don't clean it up, the second time it might fail, depending on how you try to access it.

To find out what the error message means, first, determine which system call returned the error. Then, read the man page under ERRORS to see what conditions cause that error to be set.