2

Traversing the 'zval' structure in the source code of Zend , I saw this: // zend_types.h

struct _zend_string {
   zend_refcounted_h gc;
   zend_ulong        h;                /* hash value */
   size_t            len;
   char              val[1];
};

This structure is used to store string , but 'char val[1] ' seems awkward How it is used ?

enamel
  • 81
  • 6
  • Search for "flexible arrays" or "the struct hack". – Blagovest Buyukliev Feb 10 '17 at 08:52
  • Could you also post the next few lines of the code? I have a feeling `val` is continued after this struct. – ctrl-shift-esc Feb 10 '17 at 08:52
  • @BlagovestBuyukliev `the struct hack`. That's the phrase I was looking for. – ctrl-shift-esc Feb 10 '17 at 08:54
  • @BlagovestBuyukliev I think there is duplicate on SO, but I would argue that it is not THAT question. – Kami Kaze Feb 10 '17 at 08:56
  • @enamel not necessary if this is deemed delete-worthy it gets deleted. Most of the time it just gets a link to another question, so if someone stumbles over this first it gets redirected – Kami Kaze Feb 10 '17 at 08:59
  • char ar[] makes sense for flexible arrays but not ar[1] – enamel Feb 10 '17 at 09:00
  • @KamiKaze: There are at least 20 variations of this question on SO, but I am not certain which one is the closest. – Blagovest Buyukliev Feb 10 '17 at 09:00
  • As I said in my answer ar[] just came available with c99 so everything that does not conform to this has to use this "hack" – Kami Kaze Feb 10 '17 at 09:01
  • @BlagovestBuyukliev yeah i tried finding the one I had in mind but had no success either. The one you linked had a similar topic but as far I have seen it didn't really answer this question. – Kami Kaze Feb 10 '17 at 09:02
  • @enamel: In pre-C99, arrays of size zero were not accepted by the compiler and this was a true "hack" in the sense that the compiler and the language spec didn't provide any "legal" means for it. – Blagovest Buyukliev Feb 10 '17 at 09:26

1 Answers1

2

Something like this is used to give access to an array of a length unknown at compile time. The struct gets its memory from malloc with a size bigger than the struct. So the array can be used to access the excess memory. lenis important to stay in the limits.

It is strange that it is a 1 element array, 0-element arrays were common for this until variable length arrays (val[]) were introduced in c99.

Kami Kaze
  • 2,069
  • 15
  • 27