使用新的位置时Sigbus
SIGBUS When Using Placement new?
我有以下代码(更新(:
#include <iostream>
#include <cassert>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <new>
struct S {
uint32_t a;
uint32_t b;
};
int main() {
const auto fd = open("/tmp/abc.txt", O_RDWR | O_CREAT, S_IRWXU);
assert(fd > 0);
void* ptr = mmap(nullptr, sizeof(S), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(MAP_FAILED != ptr);
std::cout << "address: " << ptr << std::endl;
auto tptr = new (ptr) S();
tptr->a = 99;
const auto rc = msync(&ptr, sizeof(S), MS_ASYNC);
std::cout << "msync returned " << rc << std::endl;
if (rc != 0) {
std::cout << "error code = " << errno << ": " << strerror(errno) << std::endl;
}
}
当我在GDB中运行它时,我得到了:
address: 0x7ffff7ff8000
Program received signal SIGBUS, Bus error.
0x0000000000400adb in main () at msync.cpp:20
20 auto tptr = new (ptr) S();
我看到有人提到了内存对准问题,我检查了0x7fffff7ff8000可以由2、8、16、32和64排除。还是其他?
预先感谢。
似乎您正在尝试 create 在此处写入文件并将其写入其中,因此最初它的大小为零,并且占据零存储页面。但是mmap
不能在文件的末尾写入,有效地为您分配了内存:首先,它会知道要添加多少个字节?您需要确保/tmp/abc.txt
包含一些字符,这些字符随后通过位置new
覆盖。它不能附加。
在我将8个随机字节写入/tmp/abc.txt
中后,运行您的程序成功并通过
63 00 00 00 00 00 00 00
正如我X86-64上预期的那样。然后,该程序报告您可能打算生成的msync
错误,并优雅地退出。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?
- 如何将元素添加到向量的字符串位置
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在特定位置追加 json 文件
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用新的位置时Sigbus