Deep writing data to shared memory structure in C failed

I used shm_open() to apply for a piece of shared memory in c language, and then used mmap() to convert it to the Struct MinHeap* type. Since the MinHeap struct has struct Element elementd[16] inside,how could I modify the value of elements?I did as follwed but failed when the program run into init_elm() and tried to assign the flag.


struct Element{
    int flag;
    int id;
    char name[32];
};


struct MinHeap{
    struct Element elements[16];
    int size;
    int capacity;
};

void init_elm(struct Element* elm){
    elm->flag=FREE;//---------------------------------WRONG HERE
    elm->id=-1;
    strcpy(elm->name,"Unamed");
}

void init_heap(struct MinHeap* heap){
    for(int i=0;i<CAPACITY;i++){
        init_elm(&(heap->elements[i]));
    }
    heap->elements[0].id=INT_MIN;
    heap->capacity=CAPACITY;
    heap->size=0;
}

char* shm_file = SHM_FILE_NAME;
size_t  shm_size = 32*sizeof(struct MinHeap);
key_t shm_fd = shm_open(SHM_FILE_NAME,O_CREAT|O_RDWR, 0666);
ftruncate(shm_fd,shm_size);
struct MinHeap* mhp_p = (struct MinHeap*)mmap(0,shm_size,PROT_READ,MAP_SHARED,shm_fd,0);/*MinHeap pointer to shared memory*/
init_heap(mhp_p);

>Solution :

The init elm() method appears to be proper based on the code you gave, and the statement elm->flag=FREE; ought to function as intended.

One more potential problem can be seen in the code is you are trying to modify a shared memory segment that is read-only by using the mmap() function with the PROT_READ flag. You need to use the mmap() function with the PROT_READ | PROT_WRITE flags as below

struct MinHeap* mhp_p = (struct MinHeap*)mmap(0,shm_size,PROT_READ|PROT_WRITE,MAP_SHARED,shm_fd,0);

This will allow you to modify the shared memory segment using the MinHeap pointer, including the elements of the struct Element array.

Additional suggestion

The line strcpy(elm->name,"Unamed"); in the code you submitted may be a problem. While accessing the shared memory region, a segmentation fault or other undefinable behaviour may occur if the name field of the Element struct is not properly initialised.

The shared memory region’s elements can be changed using the same syntax as a standard struct pointer. For instance, you could take the following actions to change the flag field of the first element in the shared memory region:

mhp_p->elements[0].flag = NEW_VALUE;

where NEW VALUE denotes the value that should be entered into the flag field.

Leave a Reply