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 ~