Saturday 4 October 2014

C Stuct Hack

Let's look at a nice little C structure hack which can be of use in many tricky situations.

Structures in C can also be defined as shown below
struct somestruct {
  int strlen;
  char str[0];
};

What does str[0] mean here?
      This statement is perfectly valid and it simply means that str  is a zero length array also known as flexible arrays.

Why do we need to use this?
       Say you declare a structure which looks like this
 
#define MAX_STRLEN 50
  struct somestruct {
  int strlen;
  char str[MAX_STRLEN];
 };

Whenever you declare structure, you are consuming 50 bytes for the array  str even if you don' use all of that. This is a waste of space. Flexible arrays can help you overcome this problem.

Lets look in details how to deal with the flexible arrays

I have a structure say,
struct mystruct
{
   int type;
   int length;
   char value[0];
};

sizeof(struct mystruct) will give 8 bytes since the memory for value hasn't been allotted.
The way to use these flexible arrays would be to allocate as many bytes as required for the character array "value" first and proceed.
For example:
struct mystruct* a = malloc(sizeof(struct mystruct) + value_length);
a->length = value_length;

One question that immediately comes to our mind is that,
Why do I need to do this to save memory. I can , instead define my struct as
struct mystruct
{
 int type;
 int length;
 char *value;
};

This is absolutely fine too when it comes to saving memory space. But the way u want to define it depends on the situation. Defining the struct as shown here in the latter way will make the character pointer "value" point to some place in memory randomly while in flexible arrays the memory allocated will be right after the memory allocated to type and length(which are of 4 bytes each).

To give an example of a situation where it comes handy.
Lets say I declare an array of structures (the structure has an array field), I want to populate them and write them to a file. In this kind of a situation, I would define the structure using flexible arrays.

For more details regarding zero length arrays or flexible arrays,

https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
http://www.quora.com/What-is-the-advantage-of-using-zero-length-arrays-in-C

No comments:

Post a Comment