shm_open with mmap giving bus error only in one pa

2019-09-17 03:09发布

问题:

I have the following simple program to create a shared memory. But this is giving

Bus error (core dumped)

This is happening only on one virtual machine and I tried the same code in mutiple VM and in every other machine this is working correctly. But only on one machine this issue is happening. Can anyone point me the issue. All my machines are running on 2.6.32-279.el6.x86_64 . Will this be a kernel issue or application issue?

#include<stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
        const char *shpath="/shm_path_for_data";
        void *memPtr;
        shm_unlink(shpath);
        int fd=0;
        fd = shm_open(shpath, O_RDWR|O_CREAT|O_EXCL, 0777);
        if(fd<0) {
                printf("shm_open failed\n");
                return 1;
        }
        if((ftruncate(fd, getpagesize())) <0) {
                printf("Ftruncate failed\n");
                return 1;
        }

        memPtr = mmap(NULL, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        if(memPtr == MAP_FAILED) {
                return 1;
        }
        strcpy((char *)memPtr, "test input.Just copying something\n");
        printf("mapped out: %s\n", (char *)memPtr);
}

回答1:

You are copying 50 bytes

memcpy((char *)memPtr, "test input.Just copying something\n", 50);
/* BTW: ^ this cast is unneeded */

there are only 36 available, so you are reading beyond the string literal, which is undefined behavior, that's why it works on one machine and fails on another, that's how undefined behavior behaves.

Try

strcpy((char *) memPtr, "Test input. Just copying something\n");


标签: c linux