Eddy
Eddy

Reputation: 13

shared_ptr reset throws segmentation fault

Tried this program out of curiosity to understand behavior of shared_ptr over raw pointers. I hope the problem could be double delete but here I am facing other:

MyClass *raw_ptr = new MyClass();
shared_ptr<MyClass> sptr1(raw_ptr);
shared_ptr<MyClass> sptr2 = sptr1;
cout << sptr1.use_count() << endl; // prints 2
sptr1.reset(); // occurs Segmentation Fault here

Expected Behavior: reduce the count to 1 and moves control to next line.

Solved: Actual issue is at the next line in which sptr1 accessing the public class member MyClass::a which is invalid access after reset and hence the segfault. Confused because it didn't print the cout messages.

cout << "count: "<< sptr1.use_count() 
     << "value: "<< sptr1->a; 

Upvotes: 1

Views: 1997

Answers (1)

Nikos C.
Nikos C.

Reputation: 51840

There's no issues in that code. It is perfectly fine.

So either your compiler is broken, your development environment is broken, or there's other code there you're not showing us which is responsible for the crash.

Upvotes: 1

Related Questions