0

In redis there is a struct called sdahdr:

struct sdahdr
{
int len;
int free;
char buf[];
}

Why not use char *buf instead, and why is sizeof(sdahdr) == 8 instead of 12?

Mat
  • 202,337
  • 40
  • 393
  • 406
Xpray
  • 3
  • 1
  • 2
  • 2
    Related: http://stackoverflow.com/questions/20310207/what-are-the-real-benefits-of-flexible-array-member/20310321#20310321, see linked questions also – Mat Dec 07 '13 at 15:34
  • Thanks, now I understand the whole thing! – Xpray Dec 07 '13 at 16:16

1 Answers1

3

The char buf[] is a placeholder for a string. Since the max length of the string is not known at compiletime, the struct reserves the name for it, so it can be properly adressed.

When memory is allocated at runtime, the allocation must include the length of the string plus the sizeof the struct, and then can pass around the structure with the string, accessible via the array.

 char *s = "test";
 struct sdahdr *p = malloc(sizeof(struct sdahdr)+strlen(s)+1);
 strcpy(p->buf, s);
Devolus
  • 21,661
  • 13
  • 66
  • 113
  • Thanks for your reply, And I am wondering if I can only user struct sdahdr *p instead of struct sdahdr p, the latter form can't be well addressed at buf? – Xpray Dec 07 '13 at 15:46
  • You'r welcome. Would be nice to accept the answer if it helped you. – Devolus Dec 07 '13 at 15:46
  • @Xpray there is also an official documentation called [Hacking Strings](http://redis.io/topics/internals-sds) that you may want to browse in addition. – deltheil Dec 07 '13 at 17:06