'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(" ");
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source