Question

I got a struct which contains multiple array members. Size of the array member is not static but it will be dynamic which shall be determined at runtime

struct was declared like this

typedef struct
{
  typea mem[MAXLEN];
  typeb mem1[MAXLEN]
  typec no[MAXLEN + 1]
  int code
}T;

but now MAXLEN is not a constant and size of arrays will be determined at runtime so I changed the declaration to

typedef struct
{
  typea *mem;
  typeb *mem1;
  typec *no;
  int code
}T;

Problem is this struct is shared with other processes using shared memory and also sent over socket so by changing array to pointer struct members are not continuous so I can't send them in single msgsend. No need to send MAXLEN as it is also present on client side only content must be sent over socket and also shared using mmap call. How to do this with minimum changes? Thanks

Was it helpful?

Solution

You can allocate the structure and all it's data as one large chunk of memory, and just make the pointers point to the correct offset. Then it's easy to "send" all data at once.

Something like

size_t size = sizeof(T) + sizeof(typea) * MAXLEN + sizeof(typeb) * MAXLEN + sizeof(typec) * (MAXLEN + 1);
char *base = malloc(size);

T *t = (T *) base;
t->mem  = (typea *) (base + sizeof(T));
t->mem1 = (typeb *) (base + sizeof(T) + sizeof(typea) * MAXLEN);
t->no   = (typec *) (base + sizeof(T) + sizeof(typea) * MAXLEN + sizeof(typeb) * MAXLEN);

When sending over socket, the receiving size knows MAXLEN and so knows how much it should receive. Then it it does the same with the allocation and the member assignment, and can in theory do a single receive call to receive all data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top