2
votes

we have couple of C applications which talk using the shared memory. first application adds the message and the second one always reads from the shared memory.

struct messagestruct {
 unsigned int sessionid;
 uint8_t message[16]; //unsigned 8bit int
}__attribute__ ((__packed__));

we need to have 3 sessions (for 3 users). so defined shared memory size as

#define SHARED_SIZE ( 3 *  sizeof(messagestruct)) + sizeof(int)

we access the shared memory as

int sesskey = ftok("/path/to/a/file", "B");
int shmemoryid = shmget(sesskey, SHARED_SIZE, 0666 | IPC_CREAT);    

during copying structs to shared memory, valgrind reports error (invalid write size 1)

void *shmaddr = shmat(shmemoryid, NULL, 0);
int *sessnum;
struct messagestruct *msgstruct;
sessnum = (int *)shmaddr;
msgstruct = (struct messagestruct*)((void*) shmaddr + sizeof(int));   
memcpy(shmaddr, currentsessionsstruct, SHARED_SIZE); //-->valgrind error invalid write size 1

thanks for any helpful info.

1
How big is the memory block you try to write to? - sharptooth
@Heandel struct messagestruct currentsessionsstruct[3]; - ramtheconqueror
@sharptooth SHARED_SIZE is the size we share between apps. one writes to that memory block & other reads from it. using semaphores to lock & unlock memory segment - ramtheconqueror
Great, but do you call shmget() asking it for enough memory? - sharptooth

1 Answers

3
votes
memcpy(shmaddr, currentsessionsstruct, SHARED_SIZE);

You are copying 3 * sizeof(messagestruct) + sizeof(int). I believe you want to copy only sizeof(currentsessionstruct).