Shared Memory in C (sysV)

407 views Asked by At
struct shared_memory_t {
    int value1; 
    int value2;
    char* buffer; 
};

shmid = shmget(key, sizeof(shared_memory_t) + segsize, 0666|IPC_CREAT);
shared_memory_t* mem = (shared_memory_t*) shmat(*shmid, NULL, 0);

So I was trying to map the shared memory to a custom structure. Now I do not know how large the segsize is until user starts program and inputs a value. I wanted buffer to be pointer to beginning of the memory space after the int values. Now if I do this I get memory faults. I can attach it and get the starting memory space with:

void* mem = shmat(shmid, NULL, 0);

Any hints on how I can get it in a state where I can do mem->value1 and access the data buffer for raw data bytes?

1

There are 1 answers

1
Nate Eldredge On

Use a flexible array member:

struct shared_memory_t {
    int value1; 
    int value2;
    char buffer[]; // flexible array member
};

shmid = shmget(key, sizeof(shared_memory_t) + segsize, 0666|IPC_CREAT);
shared_memory_t* mem = (shared_memory_t*) shmat(shmid, NULL, 0);
memset(mem.buffer, 42, segsize); // all valid