kev670
kev670

Reputation: 880

C memory sharing problems

I'm writing a shared memory program that on one side will create a piece of memory and write a struct to it and then read that struct from the other program. My problem is I cant seem to just copy a simmple vairiable into the struct without getting a segmentation fault nevermind copying the struct into the shared piece of memory. Can anyone help me out a little. Thanks

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <unistd.h>


struct companyInfo
{
    double sharePrice;
    char companyName[100];
}; 

int main()
{
    key_t key = 1234;
    int shmid;
    char* smPtr = NULL;
    int i = 1;
    struct companyInfo * pdata;
    size_t sizeOfCompanyInfo = sizeof(pdata);

    printf("Size: %d\n", sizeOfCompanyInfo);

    size_t sizeMem = sizeOfCompanyInfo*5;

    shmid = shmget(key, sizeMem, 0644 | IPC_CREAT);

    smPtr = (char*) shmat(shmid, (void*) 0, 0);

    char bank[100] = "AIB";

    strcpy(pdata->companyName, bank);


}

Upvotes: 1

Views: 114

Answers (2)

harald
harald

Reputation: 6126

pdata is not initialized, and sizeOfCompanyInfo is initialized wrong. Try this:

struct companyInfo * pdata;
size_t sizeOfCompanyInfo = sizeof *pdata;
...
shmid = shmget(....);
pdata = shmat(shmid, NULL, 0);
strcpy(pdata->companyName, "Hello there");

That said, I would probably just use sizeof *pdata instead of sizeOfCompanyInfo. It's just as readable, makes for one less variable and one less thing that can be wrong.

Upvotes: 1

djna
djna

Reputation: 55897

You mean

size_t sizeOfCompanyInfo = sizeof(*pdata);

That is the size of what pdata points to

Upvotes: 3

Related Questions