C + + enables struct objects to have a variable size array (detailed) _c language

Source: Internet
Author: User

First excerpt from the "Inside" C + + Object Model in the passage:

The array of single elements is placed at the end of a struct, so each struct objects can have a variable size array:

struct mumble {

  char pc[1];

Gets a string and then configures enough memory for the struct itself and the string

struct mumble *pmumbl = (struct mumble*) malloc (sizeof (struct mumble
) + Strlen (String) + 1);

strcpy (pmumbl->pc, String);

The book has been very clear, but the personal understanding of the beginning of a problem, mistakenly believe that the Mumble object of the PC members on the stack, the strcpy operation caused an array overflow and overwrite the subsequent memory.

Actually the object pointer PMUMBL memory is all on the heap, as shown in the following illustration:

The pointer pmumbl to the entire memory allocated by the malloc, and pmumbl->pc points to the first byte of the memory, because the malloc operation allocates enough memory for the entire string, so while the strcpy is overflowing the memory range of the PC, But there is no overflow struct memory range, make the result of strcpy is reasonable and controllable. Thus, the equivalent of struct has a variable size array, more flexible.

The above is a small series for everyone to bring the C + + so that the struct object has a variable size array (detailed) the entire content, I hope that we support cloud-Habitat Community ~

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.