【发布时间】:2020-06-17 16:42:00
【问题描述】:
更新:修正malloc(sizeof(500))后仍然存在分段错误
我在以下代码中遇到分段错误:
#include <iostream>
#include <vector>
#include <functional>
struct Data {
std::string name;
std::function<int()> work;
std::vector<int*> v1 {nullptr, nullptr, nullptr, nullptr};
std::vector<int*> v2 {nullptr, nullptr, nullptr, nullptr};
int* v3 {nullptr};
int* v4 {nullptr};
};
int main() {
std::cout << sizeof(Data) << "\n"; // Just to make sure sizeof(Data) < 500
auto raw = malloc(500); // Allocate memory
auto int_ptr = static_cast<int*>(raw);
int_ptr ++;
auto ptr = reinterpret_cast<Data*>(int_ptr);
new (ptr) Data(); // GDB reports segmentation fault here
free(raw);
}
编译命令:
clang++-9 -std=c++14 -stdlib=libc++ -ggdb3 prog.cpp -lc++abi -O2
我认为内存应该足够大,可以存储Data,但是为什么new会出现分段错误?
【问题讨论】:
-
可能的对齐问题?
-
godbolt.org/z/m36kaz: 错误:malloc.c:2401: sysmalloc: 断言`(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' 失败。
-
在我纠正错字
sizeof(500)后,编译器探索没有断言错误。但是分段错误仍然存在。 -
你有分段错误的回溯(
btin gdb)吗?
标签: c++ pointers segmentation-fault malloc reinterpret-cast