Pointer dangling bug caused by unique_ptr assignment to shared_ptr

Source: Internet
Author: User
Tags garbage collection

C + + is the most powerful and troublesome relative to other OOP languages to handle garbage collection on its own. Random allocation of memory, the full text of the various pointers will appear wild pointer (dangling pointer) or memory leaks. I've had this pain recently when I was maintaining a server project in the house.
When you start the server, it crashes for a while, and the Output window finds that the stack is corrupted, vs is a friendly reminder exe, or a bug in the loaded DLL (totally nonsense). OK, it's a memory problem, so there should be three possibilities: 1, memory out of bounds, 2, Access wild pointer 3, multithreading access to non-thread-safe pointers (multi-threaded access to static global zones or memory on heap). Determine the problem after one by one troubleshooting, but did not find a clue, because every time the collapse of the inconsistencies, then can be determined that there must be a wild pointer, but because the server program opened 20 threads, so bite the bullet to start tracking procedures, and finally find out the problem. Take a look at the following code:

' Unique_ptr<internalmessage> uptrmessage;
  Shared_ptr<internalmessage> Sptrmessage (Uptrmessage.get ())

This code may make you aware of the problem at a glance, Uptrmessage releases the memory of the pointer when it is destructor, at which point the sptrmessage pointer becomes a dangling pointer. If you continue to use Sptrmessage, it is strange that pointing to the memory area of the operating system or other protected areas may lead to fatal errors (the file is protected by the operating system). So use the smart pointer when you don't think it's all right, or be careful.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.