4 ms·
Even simpler, you can do something like this to have length-delimited AND null-terminated strings (written from memory, no guarantees of correctness etc.):
by userbinator 9mo 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));
}
- jkercher 9mo agoOne of the advantages to the pointer + length approach is free substrings. This inline approach doesn't allow that.
- WalterBright 9mo agoThe ability to slice substrings results in a massive speed increase for string handling.