I have a data structure as follows:
struct s1{
unsigned char* ptr;//points to an element in the shared memory
};
struct s1* s1Arr;
And I allocated a shared memory block and the pointer to it is:
unsigned char* shm_ptr.
I have an array of s1, with the same number of elements as there are elements in the shm_ptr array I allocated.
//point all the ptr elements of the struct to the shared memory elements(parallel array)
for(i = 0; i < count; i++)
{
shm_ptr[i] = 99;
s1Arr[i].ptr = &shm_ptr[i];
printf("val=%d\n". *s1Arr[i].ptr);
}
When I go to print *s1Arr[i].ptr, it only prints i, where i is 0, 1…while it should be printing 99.
Any thoughts as to what I am doing wrong?
I know the shared memory is working as I have tried to access it from another process.
void* allocArray_shared(int elementCount, int elementByteSize, int* shmid, key_t key)
{
printf("allocshared errno=%d\n", errno);
//size of entire array(cols*rows* byte size + row pointers)
int array_size = elementByteSize * elementCount;
//Allocate enough space for all elements + row pointers
*shmid = shmget(key, array_size, 0666 | IPC_CREAT);
char * arr = (char*)shmat(*shmid, NULL, 0);
if(!arr) return NULL;
printf("allocshared end errno=%d\n", errno);
//Return the pointer to the first row pointer
return (void*)arr;
}
EDIT:
Found the issue..was allocating multiple shared memory segments with the same key and thus reads/writes were overlapping…ugh…
I get 99 displayed 5 times with this code. I think the only change is that I removed the keyword
structfrom the beginning of your struct array declaration (it wasstruct s1 * s1Arr).EDIT: I put the
structkeyword back in and got the same result, so I don’t really know why my results are different than yours.