0

I wanna use int array in shared memory,after writing 1,2,3 into it,I expect read it like this:1,2,3.But I read this:3,2,1.I don't know why

write code:
int *gIn;
int main(){
    int id;
    id = shmget(0x666,1024,IPC_CREAT|0666);
    gIn=(int *)shmat(id,NULL,0);

    *gIn++=10;
    *gIn++=20;
    *gIn++=30;
    sleep(10);
    return 0;
}

read code:
int *gIn;
int main(){
    int id;
    id = shmget(0x666,1024,IPC_CREAT|0666);
    gIn=(int *)shmat(id,NULL,0);

    printf("%d|%d|%d\n",*gIn++,*gIn++,*gIn++);
    return 0;
}

I expect the output of read process to be 10|20|30,but the actual output is 30|20|10.It's very strange.I don't know why

wwwpy666
  • 3
  • 1

1 Answers1

3

The problem is this line: printf("%d|%d|%d\n",*gIn++,*gIn++,*gIn++);. The order of evaluation for the parameters to printf is implementation defined. In your case it just happens to do this in an order you didn't expect.

Suggest you pull out the values separately before the printf in local variables (or an array) and then print the value.

Bo R
  • 2,334
  • 1
  • 9
  • 17
  • 1
    ... or `printf("%d|", *gIn++); printf("%d|", *gIn++); printf("%d\n", *gIn++);`. – Clifford Jul 16 '19 at 05:58
  • I can't image any order can lead to this result..could you explain more specifically,thank you. – wwwpy666 Jul 16 '19 at 11:01
  • @wwwpy666 The output from `#include int main(void) { int someMemory[3] = {1, 2, 3}; int *gIn = someMemory; printf("First attempt: %d %d %d\n", *gIn++, *gIn++, *gIn); gIn = someMemory; printf("Second attempt: %d ", *gIn++); printf("%d ", *gIn++); printf("%d\n", *gIn); }`is either `First attempt: 2 1 1 Second attempt: 1 2 3` (as on my Intel/linux/gcc machine) OR `First attempt: 1 2 3 Second attempt: 1 2 3`. Both outputs are valid. – Bo R Jul 16 '19 at 16:01