在C中使用memset()时出现总线错误?

时间:2015-08-06 23:34:21

标签: c shared-memory mmap memset bus-error

我正在创建一个使用共享内存和mmap在不同进程/线程之间进行通信的程序,但我在运行时不断收到总线错误。我已经隔离了错误,它似乎发生在memset()执行后。我是否错误地设置了内存映射?  unsigned char * create_bitmap(unsigned long max)

 92 unsigned char *create_bitmap(unsigned long max)
 93 {
 94     int fd;
 95     unsigned long object_size = (max + 1) * sizeof(unsigned char);
 96     unsigned char *address;
 97
 98 //  fd = open("/dev/zero",O_RDWR);
 99     fd = shm_open("./morriluk_bitmap", O_RDWR|O_CREAT , S_IRUSR|S_IWUSR );
100     if(fd == -1){
101         perror("Unable to open morriluk_bitmap");
102         exit(EXIT_FAILURE);
103     }
104     printf("1\n");
105     if(ftruncate(fd, object_size) == -1){
106         perror("Unable to resize morriluk_bitmap");
107         exit(EXIT_FAILURE);
108     }
109     printf("2\n");
110
111     address = (unsigned char*)mmap(NULL, object_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
112     if (address == MAP_FAILED) {
113         perror("Unable to mmap morriluk_bitmap to any address");
114         exit(EXIT_FAILURE);
115     }
116     printf("3\n");
117
118     memset((void *)address, PRIME, object_size);
119     printf("4\n");
120
121     return address;
122 }

命令行输出:

creating bitmap
1
2
3
Bus error (core dumped)

1 个答案:

答案 0 :(得分:0)

I'll tell you one thing you should do, that's flushing and syncing the output buffers. It may well be that you are actually printing 4 but it's being lost because of the crash.

In other words, wherever you have:

printf("something");

change it to:

printf("something"); fflush(stdout); fsync(fileno(stdout));

This will ensure that the buffers are flushed because, if they're not when you crash, you may well lose the information. The fsync() itself may not be necessary, I use it just to be safe.