Pointer to middle of allocation, part 1

The Redis “Simple Dynamic String” is a length-prefixed string, roughly like this:

struct sds {
  size_t len;
  char buf[];
};

If you have a pointer to an sds object, where in the allocation does the pointer point to? You would think ot points to the beginning: this is how C normally works, and this is how malloc and free work. But Redis does things differently: instead, it passes around pointers to the buf field, of type char*:

                 |
                 v
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| len           | buf                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Why? So that Redis can then use its SDS strings as normal C-strings, passing them to C functions (strcpy, strcmp, and so on).

I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.