Click to See Complete Forum and Search --> : shared message not right size(C/C++)


tecknophreak
10-02-2002, 09:48 PM
i'm working in rh7.1 and this is the second time i'm having problems with the size of things. i'm trying to create a shared memory space of 1MB, which should be fine according to /proc/sys/kernel/shmmax(it reports 32 MB). when i run the following program i get to 4685 and then i get a seg fault.

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdexcept>
#include "test.h"
void getMem(void*, bufferStruct*, int&, bool);

int main() {
void *shared_memory1((void *)0), *shared_memory2((void *)0);
bufferStruct *shBuff[2];
bufferStruct buff;
int shmid[2];
getMem(shared_memory1, shBuff[0], shmid[0], 0);
getMem(shared_memory2, shBuff[1], shmid[1], 1);
for (int i = 0; i < 512*1024; ++i)
buff.data[i] = i + 1;
for (int i = 0; i < 512 * 1024; ++i) {
cout << "i " << i << endl;
shBuff[0]->data[i] = buff.data[i];
}

}


void getMem(void *shared_memory, bufferStruct *shBuff, int &shmid, bool which) {
srand((unsigned int)getpid());
shmid = shmget((key_t)(1260 + which), 1024 * 1024, 0666 | IPC_CREAT);
cout << "shmid " << shmid << endl;
if (shmid == -1) {
cerr << "Shared Memory fault" << endl;
exit(1);
}
shared_memory = shmat(shmid, (void *)0, 0);
if (shared_memory == (void *)-1) {
cerr << "Shared Memory fault" << endl;
exit(1);
}
shBuff = (bufferStruct *)shared_memory;
}


bufferStruct looks like

struct bufferStruct {
unsigned short data[512 * 1024];
}

and it's held in test.h

Energon
10-03-2002, 11:54 AM
Well, the first thing is that magic numbers are really, really bad. Use constants so it's easier to figure out some of what you're doing.

Right now, I'd be concerned about the size you're allocating. 1024*1024 is not necessarily as big as sizeof(struct bufferStruct)+(sizeof(unsigned short)*512*1024), which is the size of your structure data.

I don't know if that'll fix it, but right now that's what stands out as a possible bad spot.

You could also create a new bufferStruct, make your array a pointer, allocate the shared memory for just the array (sizeof(unsigned short)*512*1024), and set that pointer rather than worrying about allocating shared memory that you don't need (the 32MB limit is constant no matter how much RAM you throw at shared memory).