From dfb93e636657c59e89fc62002ac26dee1795b794 Mon Sep 17 00:00:00 2001 From: Andrew Clayton Date: Fri, 7 Mar 2025 00:49:45 +0000 Subject: Initial commit Signed-off-by: Andrew Clayton --- sptr.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 sptr.c (limited to 'sptr.c') diff --git a/sptr.c b/sptr.c new file mode 100644 index 0000000..c275b8a --- /dev/null +++ b/sptr.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +union sptr_u { + uint8_t base[1]; + uint32_t offset; +}; +typedef union sptr_u sptr_t; + +struct s { + uint8_t name1_len; + uint8_t name2_len; + uint8_t name3_len; + + sptr_t name1; + sptr_t name2; + sptr_t name3; +}; + +static void sptr_set(sptr_t *sptr, void *ptr) +{ + sptr->offset = (uint8_t *)ptr - sptr->base; + + printf("sptr->base : %p\n", sptr->base); + printf("sptr->offset : %u\n", sptr->offset); +} + +static void *sptr_get(sptr_t *sptr) +{ + return sptr->base + sptr->offset; +} + +int main(void) +{ + static const char * const names[] = { "toor", "foobar", "baz" }; + struct s *s = malloc(sizeof(struct s) + + strlen(names[0]) + strlen(names[1]) + + strlen(names[2]) + 3); + char *p = (char *)(s) + sizeof(struct s); + + printf("s : %p\n", s); + + s->name1_len = strlen(names[0]); + sptr_set(&s->name1, p); + p = stpcpy(p, names[0]); + + p++; + s->name2_len = strlen(names[1]); + sptr_set(&s->name2, p); + p = stpcpy(p, names[1]); + + p++; + s->name3_len = strlen(names[2]); + sptr_set(&s->name3, p); + p = stpcpy(p, names[2]); + + printf("name1 : %s\n", (const char *)sptr_get(&s->name1)); + printf("name2 : %s\n", (const char *)sptr_get(&s->name2)); + printf("name3 : %s\n", (const char *)sptr_get(&s->name3)); + + free(s); + + exit(EXIT_SUCCESS); +} -- cgit