What could be the possible reasons for segmentation fault?

Shmget() help! Segmentation Fault....?

  • I have a project dealing with shared memory in c++ (using Solaris) and I have the following code to create my shared memory segment but it's giving me a segmentation fault when I try to create the shared memory. I printed out the value of shmget() and it returned a value of -1 so obviously it failed but I have no idea what could be causing it. This was code given as an example in our text book to better understand shared memory: //Create Shared memory int segment_id; char *shared_memory; int size =4096; segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR); cout << "segment_id: " << segment_id<<endl; //test code returned a -1 shared_memory = (char *)shmat(segment_id, NULL, 0); sprintf(shared_memory, "TESTING!"); cout << "SHARED_MEMORY :" << shared_memory <<endl; //test code to print sharedMem I even tried setting my char *shared_memory = new char[SOME_SIZE] before i used it but I don't think that's quite the problem. the shmget is. Any help would be greatly appreciated! :)

  • Answer:

    You state that shmget failed (returned -1). This is because you try to open an non-existing shm region. Atleast one process should use the IPC_CREAT (like open, not CREATE!) flag in the third arg of shmget. Multiple processes may do so unless you also use IPC_EXCL. (and don't use the IPC_PRIVATE key) segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR|IPC_CREAT); More info: man shmget Additional tip: get your page size from sysconf(_SC_PAGESIZE), don't hardwire 4096. Or atleast use the PAGE_SIZE macro. Hope this helps.

beTi at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.