Thread: Problem with shared memory

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    101

    Problem with shared memory

    I'm trying to use shared memory. So far I have
    Code:
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_PATH_LEN 1024
    #define ARRAY_SIZE 50
    
    typedef struct _task{
    	char path [MAX_PATH_LEN];
    	char thread_id[MAX_PATH_LEN];
    	char op;
    	int index;
    }task;
    
    typedef struct _sharedMem{
    	int lastIn;
    	int numTasks;
    	sem_t mutex;
    	int size;
    	task array [ARRAY_SIZE];
    }sharedMem;
    
    int main(void){
    	int i;
    	int id = shmget(1234, sizeof(sharedMem), IPC_CREAT|0777);
    	sharedMem* shMem = shmat(id, NULL, 0);
    	printf("init 1\n");
    	shMem->lastIn = 0;
    	printf("init 2\n");
    	shMem->numTasks = 0;
    	printf("init 3\n");
    	sem_init(&(shMem->mutex), 0, 1);
    	printf("init 4\n");
    	shMem->size = ARRAY_SIZE;
    	for(i = 0; i < shMem->size; i++){
    		strcpy(shMem->array[i].path, " ");
    	}
    	return 1;
    }
    The output for this is
    Code:
    init 1
    Segmentation fault
    I have no idea why. Do we have to do something to the structure before start using it?
    If so what?

  2. #2
    Registered User
    Join Date
    Apr 2008
    Posts
    396
    You should check all the system calls status, are you sure your shm object is correctly created and attached? no.

    PS: you should use ftok() to create a key_t typed object instead of '1234', because some values are reserved
    Last edited by root4; 01-06-2009 at 12:47 PM.

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    For reference:
    ftok() gets you a key_t value - to then pass to semget() for a valid shmid - which can then be passed to shmat().

    The other Posix API for shared memory is shm_open(), mmap(), and shm_unlink().

    Do yourself a big favor and get into the habit of always checking return values and error codes.

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  2. Partly shared memory
    By DrSnuggles in forum C++ Programming
    Replies: 13
    Last Post: 01-21-2009, 03:35 AM
  3. Memory leaks problem in C -- Help please
    By Amely in forum C Programming
    Replies: 14
    Last Post: 05-21-2008, 11:16 AM
  4. Shared memory woes
    By joshdick in forum C Programming
    Replies: 4
    Last Post: 07-28-2005, 08:59 AM
  5. Memory Problem - I think...
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 10-24-2001, 12:14 PM