1

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(" ");
}
3
  • You aren't checking for any errors. Commented Oct 25, 2014 at 17:00
  • @o11c what kind of errors? Commented Oct 25, 2014 at 17:05
  • functions such as ftok, shmget may all return errors. Checking for errors is NOT optional. Commented Oct 25, 2014 at 21:32

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great, I added the square brackets and modify a bit the code. Thanks @codenheim

Your Answer

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.