UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2008-11-18 01:39 PM

lvasilis22
Member
Registered: 2008-11-17
Posts: 8

Re: shared memory

int i,shmid[2];
char *shmem[2];
key_t shmkey[2];

for (i=0;i<=2;i++) {
if ((shmid[i] = shmget(shmkey[i], SHMSIZ, PERMS | IPC_CREAT)) < 0) {
perror("shmget"); 
exit(-1); }
printf("Created shared memory region No:%d with identifier %d\n",i,shmid[i]);
if ((shmem[i] = shmat(shmid[i], (char *) 0, 0)) == (char *) -1) {
perror("shmat"); 
exit(-1); }
printf("Attached shared memory region No:%d\n",i);
}

Offline

#2 2008-11-18 04:18 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: shared memory

Um, your loop is doing 3 iterations: 0, 1, and 2...  So, of course you need 3 elements
in your arrays that you're accessing with that loop index...

The reason it doesn't seg-fault in the modified code, even though you failed to increase
the size of the "shmkey" array to 3 as well, is simply due to how your compiler organized
the layout of your variables, such that writing off the end of that array only ends up
trashing other variables of yours, and NOT trashing anything really important like your
stack frame return address...  But, regardless, seg-fault or not, it's still wrong and
you're still trashing some other variable of yours with the incorrectly sized "shmkey"
array...

Offline

#3 2008-11-18 05:45 PM

lvasilis22
Member
Registered: 2008-11-17
Posts: 8

Re: shared memory

/* Creation of 3 different unique keys for the three different memory segments */
for (i=0;i<3;i++) {
if ((shmkey[i] = ftok(".",i+1)) == (key_t) -1) {
    perror("IPC error: ftok"); 
	exit(1); } }

Offline

Board footer

Powered by FluxBB