Struct member in memory offset calc

Source: Internet
Author: User

If you wrote some struct whatever in C or C ++ style.

Please be careful for those in memory bug.

1) determine the struct stra {int A; int B; double C ;}; it was used by some software and give it to users based on the memory transformation of the struct. after something happened, stra changedstra {int A; int B; double C; long d ;}; how to judge stra now hold "D" or not? # Ifdef _ win64 # define offsetof (S, m) (size_t) (ptrdiff_t) & reinterpret_cast <const volatile char &> (S *) 0) -> m) # else # define offsetof (S, m) (size_t) & reinterpret_cast <const volatile char &> (S *) 0) -> m) # endif2. structure upgrade (I mean to extend from C style to C ++ style). After reading the above, someone may find that this part does not need to be further investigated. However, I found a bug in the software today. When I upgraded struct to C ++ style, I found that I could delete it. Now I should have a virtual destructor for struct, delete memory crash. Struct stra {int A; int B; stra () {memset (this, 0, sizeof (stra) ;}// the error here is obvious, I put it in the case that I did it when I needed set 0. As a result, debug took a long time to suspect that it was the problem. Virtual ~ Stra () ;}; but we stra * P = new stra (); xxxxnice_remove (p); // crash. cause: the vptr pointer in the virtual destructor is set to zero at memset, which means this pointer cannot be used, but this risk is triggered when you delete p. Improvement: 1. Do not be virtual (stupid ). 2. do not construct functions (note that I mean not to use memset for base struct). At the same time, set the destructor to pure virtual, and then perform the memset operation to assign the child struct the new and delete operations, this not only retains the core functions of stra, but also avoids the issue of virtual function table structure errors in the base class.

Struct member in memory offset calc

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.