Is this how one can use the the "extra" memory allocated while using the C struct hack?
Questions:
I have a C struct hack implementation below. My question is how can I use the "extra" memory that I have allocated with the hack. Can someone please give me an example on using that extra memory ?
#include<stdio.h> #include<stdlib.h> int main() { struct mystruct { int len; char chararray[1]; }; struct mystruct *ptr = malloc(sizeof(struct mystruct) + 10 - 1); ptr->len=10; ptr->chararray[0] = 'a'; ptr->chararray[1] = 'b'; ptr->chararray[2] = 'c'; ptr->chararray[3] = 'd'; ptr->chararray[4] = 'e'; ptr->chararray[5] = 'f'; ptr->chararray[6] = 'g'; ptr->chararray[7] = 'h'; ptr->chararray[8] = 'i'; ptr->chararray[9] = 'j'; }
“Struct Hack” technique is used to create variable length member in a structure. In the above structure, string length of “name” is not fixed, so we can use “name” as variable length array. Let us see below memory allocation. struct employee *e = malloc(sizeof(*e) + sizeof(char) * 128);
Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language. For the structures in C programming language from C99 standard onwards, we can declare an array without a dimension and whose size is flexible in nature.
Yes, that is (and was) the standard way in C
to create and process a variably-sized struct
.
That example is a bit verbose. Most programmers would handle it more deftly:
struct mystruct { int len; char chararray[1]; // some compilers would allow [0] here }; char *msg = "abcdefghi"; int n = strlen (msg); struct mystruct *ptr = malloc(sizeof(struct mystruct) + n + 1); ptr->len = n; strcpy (ptr->chararray, msg); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With