Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.

The ability to slice substrings results in a massive speed increase for string handling.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: