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 it 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).

Tagged #redis, #data-structures, #pointers, #c, #programming.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2016. Content is not associated with my employer. Found an error? Edit this page.