segment fault because shared_ptr - majianpeng/majianpeng.github.io GitHub Wiki
#include <condition_variable>
#include <thread>
#include <chrono>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <set>
#include <climits>
using namespace std;
struct A {
public:
A(int i) : seq(i) {
}
int seq;
shared_ptr<A> next = nullptr;
};
int main() {
int cnt = 22800;
shared_ptr<A> head = nullptr, tail = nullptr;
`while (cnt < (INT_MAX - 2000)) {`
`head = tail = make_shared<A>(0);`
`for (int i = 1; i < cnt; i++) {`
`tail->next = make_shared<A>(i);`
`tail = tail->next;`
`}`
`head = nullptr;`
`printf("%d\n", cnt);`
`cnt+=100;`
`}`
`return 0;`
}
When head=nullptr, it will call destructor of A and call destructor of A.next. If A.next is not nullptr. It will decease reference of A.next and after decrease if A.next == nullptr, it continue calldestructor of A.next. The destructor will be called until the last one. Due to too many stacks cause segment fault .
(gdb) down
#27799 0x00000000004027f5 in std::allocator_traits<std::allocator<A> >::destroy<A> (__a=..., __p=0x4fb2a0) at /usr/include/c++/11/bits/alloc_traits.h:531
总共有27799 stack frame.