简体   繁体   中英

write to shared memory segmentation fault

all I want to do is just write "hey" to my shared memory, but it gets thrown at that line. very simple code as follows:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
#define FLAGS IPC_CREAT | 0644
int main(){
    key_t key;
    int shmid;
    if ((key = ftok("ex31.c", 'k')) == -1){ 
        exit(1);}        
    if ((shmid = shmget(key, SHM_SIZE, FLAGS)) == -1) {
            exit(1);}
    char* shmaddr;
    if( shmaddr=shmat(shmid,0,0) == (char*)-1){   //WRONG ARGUMENTS ??
            exit(0); }
    printf("opened shared memory\n");  //gets here
    strcpy(shmaddr, "hey");     //GETS THROWN HERE
    printf("after writing to memory\n"); //never get here

the error the debugger gives me is:

Program received signal SIGSEGV, Segmentation fault. 0x0000000000401966 in main (argc=1, argv=0x7fffffffe068) at ../ex31.c:449 449 strcpy(shmaddr, "hey"); //GETS THROWN HERE

The problem is operator precedence. In the line

shmaddr=shmat(shmid,0,0) == (char*)-1)

Then the unary - operator and the cast operator have the highest precedence, followed by == , followed by = which has the lowest precedence. So your code turns out to be equal to

shmaddr=(shmat(shmid,0,0) == (char*)-1))

which is nonsense.

Assignment inside conditions is very bad programming practice . Every half-decent compiler will give you a warning if you try it. Apart from operator precedence issues, it is easy to mix up = and ==. Also, the = operator introduces a side effect to the expression, so mixing it with other operators could cause undefined behavior. And perhaps most importantly, putting = inside conditions usually reduce code readability quite a lot.

Your code should be written as:

shmaddr = shmat(shmid,0,0);
if(chmaddr  == (char*)-1){

It is important to understand that you gain nothing by merging these 2 rows into 1. The generated machine code will be identical, apart from the lack of bugs in the above version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM