Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct hack at work

Tags:

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';   } 
like image 654
Ankur Agarwal Avatar asked May 14 '13 21:05

Ankur Agarwal


People also ask

What is struct hack in C?

“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);

What is flexible array in C?

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.


1 Answers

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); } 
like image 75
wallyk Avatar answered Oct 06 '22 00:10

wallyk