I'm trying to share memory between processes to "efficiently" count string repetitions coming from a file with a random number of strings. So, let's say that I got all of them in char** words and I want to have two variables of different types to share (WordStruct shared and int shared_length), the first one makes reference to a structure that has the position of the string in words and it's occurrence, while the second makes reference to the amount of strings that are different. This is because I want to iterate shared and know when to stop, however, the problem appears when I'm trying to set shared_length to a value.
This is my code:
typedef struct wordSturct {
int word_id;
int count;
} WordStruct;
/* open file */
int index = 0;
char* word = malloc(sizeof(char) * 257);
char** words = malloc(sizeof(char*) * buffer) /* lets say buffer is way to big */
while (fscanf(fp, "%s", word) == 1) { /* fp is a FILE* */
words[index] = malloc(sizeof(char) * 257);
strcpy(words[index], word);
index++;
}
key_t key = ftok("/tmp", 'F');
int identifier = shmget(key, sizeof(WordStruct) * index + sizeof(int), IPC_CREAT | SHM_W | SHM_R);
void* shared_memory = shmat(identifier, NULL, 0);
WordStruct* shared = (WordStruct *) shared_memory;
int* shared_length = (int *) (shared + sizeof(WordStruct) * index);
From here on, I'm putting some testing code to make sure about the correct functionality of the shared memory segment, so lets think that there are no repeated words, so iterating shared till index would be correct:
for (int i=0; i < index; i++) {
shared[i].word_id = i;
shared[i].count = 0;
}
Until here, everything is accepted and correctly instantiated, but then I try to do this:
*shared_length = 0; /* main.c:125 */
And I got the following error according to VALGRIND:
Invalid write of size 4
at 0x400F11: main (main.c:125)
Address 0x40d1400 is not stack'd, malloc'd or (recently) free'dProcess terminating with default action of signal 11 (SIGSEGV)
Access not within mapped region at address 0x40D1400
at 0x400F11: main (main.c:125)
...Segmentation fault (core dumped)
I've tried to setting a WrapperStruct to assign the shmat() function so that I could have only one structure, but I'ld need to know the index value before even opening the file for having my array of words, so that's not an option I think.
When you do arithmetic on pointers, it's performed in units of the size of the object that the pointer points to. So you don't need to multiply by sizeof(WordStruct)
-- that caused it to be multiplied twice, and you're going outside the shared memory. It should be:
int* shared_length = (int *) (shared + index);
or
int *shared_length = (int *)&shared[index];