[英]memset large memory region allocated by shm_open/ftruncate/mmap crashes with bus error
[英]shm_open with mmap giving bus error only in one particular machine
我有以下简单的程序来创建共享内存。 但这给
总线错误(核心已转储)
这仅在一个虚拟机上发生,并且我在多个VM中尝试了相同的代码,而在其他所有计算机上,它均正常运行。 但是仅在一台计算机上会发生此问题。 谁能指出我的问题。 我所有的机器都在2.6.32-279.el6.x86_64上运行。 这是内核问题还是应用程序问题?
#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);
}
您正在复制50个字节
memcpy((char *)memPtr, "test input.Just copying something\n", 50);
/* BTW: ^ this cast is unneeded */
只有36种可用,因此您所读的内容超出了字符串文字,这是未定义的行为,这就是为什么它在一台机器上工作而在另一台机器上失败的原因,这就是未定义行为的表现方式。
尝试
strcpy((char *) memPtr, "Test input. Just copying something\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.