1
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?

3
  • Have you read in the manual that size needs to be a multiple of a memory page size? Probably a multiple of 4096. Commented Nov 6, 2021 at 2:09
  • Also always check the return value of shmget, don't assume that it will just work. Commented Nov 6, 2021 at 2:10
  • 1
    @Cheatah: size does not have to be a multiple of the page size; the system will automatically round it up. Commented Nov 6, 2021 at 2:19

1 Answer 1

1

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

1 Comment

It really was that simple, after a couple hours reading through the manuals. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.