Comment by userbinator

10 hours ago

Even simpler, you can do something like this to have length-delimited AND null-terminated strings (written from memory, no guarantees of correctness etc.):

    char *lenstrdup(char *s) {
       int n = strlen(s);
       char *p = malloc(n + sizeof(int) + 1);
       if(p) {
          strcpy(p + sizeof(int), s);
          *(int*)p = n;
          p += sizeof(int);
       }
       return p;
    }

    void lenstrfree(char *s) {
        free(s-sizeof(int));
    }

One of the advantages to the pointer + length approach is free substrings. This inline approach doesn't allow that.