cafej
cafej

Reputation: 95

segmentation fault when accessing shared memory segment

I need to implement a program that shares information between different processes.

But when I try to access a member of the shared structure, it yields a segmentation fault.

How can i fix it? Please see my code below.

Source File:

#include <string.h>
#include <stdio.h>
#include "ShM.h"

#define SHM_SIZE 1024 

int main(){

    stablishMemory();
    Deck *deck = obtainMemory();
    strncpy(deck->cards,"carlos",SHM_SIZE);
    unlinkMemory();
    return 0;
}

Header File (ShM.h):

#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include <unistd.h>

int idMemory;

typedef struct {
    char *cards;
}Deck;

Deck* letra;
#define SHM_SIZE 1024 

void stablishMemory(){
    idMemory = shmget (obtainkey(), SHM_SIZE, 0777| IPC_CREAT);
    letra = (Deck* )shmat (idMemory, NULL,0);
}

key_t obtainkey(){
    return ftok("/bin/ls",24);
}

void unlinkMemory(){
    shmdt((Deck*)letra);

}

Deck* obtainMemory(){
    return letra;
}

void destroyMemory(){
    shmctl(idMemory, IPC_RMID, (struct shmid_ds*)NULL);
    unlink(" ");
}

Upvotes: 1

Views: 6341

Answers (1)

mrjoltcola
mrjoltcola

Reputation: 20842

This structure isn't self-contained. The structure may be within the shared memory but the pointer cards can point anywhere.

typedef struct {
    char *cards;  // the memory that cards points to could be outside the segment
} Deck;

You must alloc cards (its a dangling pointer), but more importantly, you must also alloc cards from the shared region, or make it an inline buffer (within the structure) like:

Either do:

deck = allocSharedMem(sizeof(*deck));
deck->cards = allocSharedMem(52);

or make it inline:

typedef struct {
    char cards[52];
} Deck;

Upvotes: 3

Related Questions