Skip to content

Comment on Making a StringBuffer in C, and questioning my sanityparent

Comments

you misunderstood what i said about the strlen field, but we agree, yes, it's in the header where it belongs.

I explained how returning the address of the string buffer instead of the address of the struct would give you a C compatible string that you could pass to other C library functions. If those functions are "readonly" wrt the string, everything is copasetic.

if those string functions update/write the c-string (which is in the buffer) the strlen in the header will now be wrong. That has nothing to do with my suggestion, and it's already "broken" in that way you point out. My "string free bytes field" suggestion will also be broken by an operation like that, so my suggestion does not make this data structure worse than it already is wrt compatibility with C library functions.

However that strlen and free bytes problem can be managed (no worse than C standard strings themselves) and strlen and/or free bytes are useful features that make some other things easier so overall it's a win.

I was basing my response off of this:

i did see a place to shave a byte in the sds data struct. The null terminator is a wasted field

I'm still not sure what byte in the struct you're talking about removing... because I don't see an actual null terminator field.

the word "null term" appears in the ascii art diagram, that's where the null terminator is. the strlen field is in the portion labelled header.

the strlen field can be moved to where the word "null term" appears, except with a changed semantic of "bytes remaining" so it will go to zero at the right time. now you have a single entity "bytes remaining" instead of two entities, "strlen" and "null" giving a small storage saving (there is an additional null terminator most of the time, right at the end of the string; but this doesn't take up any storage because that storage is not used for anything else)

over and out.

the word "null term" appears in the ascii art diagram

Yes but it does not appear anywhere in the struct that I can see... I would love to be proven wrong though.

the string needs a null terminator to be C-string compatible. the trick of putting a count at the end that turns into a null terminator at the right moment will save a byte, regardless of how it is labelled

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.