logoalt Hacker News

senfiajyesterday at 11:42 PM7 repliesview on HN

I wonder, why not use a string buffer paired with its length? For example, maybe use struct that has char pointer, and 2 ints (occupied length + total buffer length). Almost like c++'s std::string. This null terminator thing really sucks, it's potentially insecure and often unperformant.


Replies

maxlybberttoday at 4:06 AM

It's definitely possible. And common, at least in some projects. The only real drawback is that sloppiness will lead to multiple slightly different nonstandard string types in the same project.

bnolsentoday at 1:41 AM

That's called a fat pointer. Null terminated c strings is the majority of memory errors out there.

GalaxyNovatoday at 12:02 AM

Yes I have seen it happen a few times with `strlen` being called in a loop silently causing O(N) to turn to O(N^2)

show 3 replies
none_to_remaintoday at 12:14 AM

The size overhead of that is 2*sizeof(int) while the overhead of null termination is sizeof(char). If I remember the standard right, the former is worse by at least sizeof(char), and usually more in practice. This used to matter, sometimes still does.

show 2 replies
chiphtoday at 12:09 AM

Pascal did/does this, but eventually someone wants a string longer than the size portion can handle. Or wants the number of characters not the number of bytes.

show 3 replies
MBCooktoday at 1:55 AM

A lot of them are strings coming from or going to user space right? So wouldn’t you have to do constant conversions?