0

The question is about how the shared pointer handles the object in the following codes:

std::vector<float> vec(10); float* p = &vec[0]; std::shared_ptr<float> p_shared(p); 

The question is that whether the shared pointer p_shared still responsible for managing the vec, i.e. delete / garbage collection of vec? Is there any possibility that the vec has been deleted before the p_shared deletes vec?

2 Answers 2

2

The code you have posted will result in undefined behavior, because both the vector and the shared_ptr think they own the memory. In reality only the vector owns it, so whenever the shared_ptr goes out of scope it will delete p which is UB and your program could do anything at all, including crashing.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. So if I want to receive data from an external program via function void InputData(const float* p_data, const int bytes), other than making a copy of the data, is there any way to prevent the external data from being deleted by the external program before I am done with using the data? Is changing the function interface to void InputData(std::shared_ptr<float> p_data, const int bytes) going to fulfill the requirement because the external program is required to pass a shared pointer to InputData?
yes, passing the data as shared_ptr to a function prevents the data to be deleted externally.
1

If the program leaves the scope the vec variable will be deleted and the shared pointer will delete the pointer too. As the result the program will crash due to the double free().

However, if the shared pointer is returned to another scope, we still can use the pointer, until the shared pointer realizes that the pointer isn't used anymore, see this example below:

std::shared_ptr<float> test() { std::vector<float> vec(10); vec[0] = 10.1; vec[1] = 5.0; float* p = &vec[0]; std::shared_ptr<float> p_shared(p); cout<<"Get value 0th: "<<p_shared.get()[0]<<" , 1st: "<<p_shared.get()[1]<<endl; return p_shared; } int main() { std::shared_ptr<float> p1 = test(); p1.get()[1] = 9.0; std::cout<<"Get value 0th: "<<p1.get()[0]<<" , 1st: "<<p1.get()[1]<<std::endl; std::cout<<"End of program"<<std::endl; } 

Output:

Get value 0th: 10.1 , 1st: 5 Get value 0th: 0 , 1st: 9 End of program free(): double free detected in tcache 2 Aborted (core dumped) 

2 Comments

Thank you. It makes sense. The double free by vector deconstructor and shared pointer still result in undefined behavior after all shared pointers are released. This makes me better understand the problem.
@Charlie, please mark either my answer or John's answer as the solution oft your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.