7 ms·
the zero terminated string is I think is computing's biggest mistake. Pascal style strings were much safer.
by mrlonglong 4mo ago
the zero terminated string is I think is computing's biggest mistake. Pascal style strings were much safer.
- jackbucks 4mo agoIt was definitely an interesting way to allocate pointers. I did once have a very large project where devs didnt understand this and resolved hundreds or more off by one and memory overwrites in C due to this feature. But at the same time, I think blaming the software was kind of a cop out. Devs were in a hurry and simply didnt respect the rules. Given todays software engineer at large. Nerfing programming languages so they cant destroy things might not be a bad idea. But AI will nerf everything.
- fragmede 4mo agowhy is AI gonna nerf everything? sure it could be used as the easy button, but I just spent two hours this morning learning about the neuroscience of how memory works in the brain that I didn't mean to and now I want to run studies on how memory works. Why do you assume that AI is gonna nerf everything?
- AnimalMuppet 4mo agoAGI might. AI? No way. See, AI was trained on existing data - on all that existing C code out there (sure, and also on all the papers and articles saying what was wrong with that C code). Those bugs are in the training data, and often not marked as bugs. So when AI generates C code, is it going to avoid making the mistakes that human code made? No, it's going to generate the kind of code it was trained on. How could it be otherwise? That's not going to nerf anything.
- CamperBob2 4mo agoWhen's the last time you saw a decent coding model create a buffer-overflow bug while trying to use C strings? Serious question. Anyone else seen this happen in the last 12-18 months? If so, which model and version were you using?
- macintux 4mo agoWould you even know? Serious question. The volume of code the models can produce, the subtle ways these bugs can manifest (or even only manifest when under attack), it seems like they would be easy to overlook.
- CamperBob2 4mo agoI have a habit of getting GPT 5.5 to review everything Opus writes for me, and vice versa. The model in the reviewer role frequently finds things I overlooked myself. Occasionally in parts of the code I wrote. No modern LLM has found any buffer overflow bugs in parts of my code that originated from another LLM. Again, though, they have found one or two that were my fault.
- bigstrat2003 4mo agoHaving one clanker verify the output of another has minimal, almost non-existent, persuasive value as evidence.
- CamperBob2 4mo agoHopefully you're close enough to retirement age that it's a moot point for you. If not, you're headed for a bad time, a major attitude adjustment, or (most likely) both.
- smackeyacky 4mo agoI had Claude write a bit of stupid C# the other day that had an off by one string truncate. Surprised the hell out of me.
- krupan 4mo agoHow many people are writing C code with LLMs? I get the impression it's mostly JavaScript web apps
- 4mo ago
- deathanatos 4mo ago> See, AI was trained on existing data - on all that existing C code out there (sure, and also on all the papers and articles saying what was wrong with that C code). Those bugs are in the training data, and often not marked as bugs. So when AI generates C code, is it going to avoid making the mistakes that human code made? No, it's going to generate the kind of code it was trained on. How could it be otherwise? The generalization of this is why I think all these AI companies writing blog posts where the marketing department is just jer—ranting endlessly about how AI will improve itself into the singularity is just crazy talk. They generate a random statistically likely output, and the most statistically likely output is mid. Exceptional outputs — the ones that wow us or move the needle are exactly that, unlikely. AGI is sci-fi, and LLMs will not change that. You can see the same effect when AI emits bash, too, and especially so since most bash is terrible, and most users of bash do not put in the effort to learn bash and its foibles. So it outputs what most people write, which is not great.
- AnimalMuppet 4mo agoIt still could happen, if they had a way to judge the exceptional outputs from the mid and terrible ones. But I'm not sure they have that...
- ComputerGuru 4mo agoIn far from an AI fanatic, but I would argue training it on GitHub PRs and general software patches already provides that. Instead of just seeing the static snapshot it sees “this code was replaced by this (hopefully better) code”
- dietr1ch 4mo agoI think it was NULL itself. It was a long way until we realised we don't want invalid values and could use the type system to help us use special values safely.
- jkercher 4mo agoMeh, I think NULL is fine in C. It's an extra, valid state to represent pointers at no cost. Unlike the more hand holdy languages, it's quite rare for a pointer in C to have the ability to be NULL since, more often than not, it's pointing at something known. It's actually quite rare to see NULL checks unless it's API code or something like that. I can see this being more of a problem in a managed language where anything can be NULL at any time.
- kelnos 4mo ago> to represent pointers at no cost I wouldn't call "cause of bugs and security issues" "no cost". > it's quite rare for a pointer in C to have the ability to be NULL As a C programmer for more than 25 years, that is the exact opposite of my experience.
- UqWBcuFx6NV4r 4mo ago[flagged]
- IgorPartola 4mo agoIs None OK in Python? NULL in C just doesn’t belong at the end of a string. But IMO having a “there is no value here” designation is not a bad thing.
- none_to_remain 4mo agoI think you're mixing up the NULL pointer and the NULL (sometimes NUL) character.
- jibal 4mo ago
- themafia 4mo ago> Pascal style strings were much safer. The limitations were brutal. Initially you could only have 255 bytes in a string. The length of a string and the size of the allocation are now separate and you may need to think about that unused memory in your design. The problem now doubles with the introduction of UTF-8. Your string size is in bytes and you need to track characters separately. If you want to create an array of strings you either need to specify the length of all strings and accept the memory overhead or have an array of pointers to strings. If you use an array of pointers you may end up choosing to use the 'nil' value as a sentinel that means "end of list." So we're right back where we started. -- Because someone decided to downvote this HN has limited the speed at which I can reply. This site is tragic and I'm fully done with it now. You can spread propaganda and poorly sourced zeitgeist and be among friends but if you try to have a genuine conversation about programming languages you are made to be unwelcome immediately. Screw this. -- > No other data structure works like this. The linked list. > You can't mess this up in an array C happily decomposes arrays into pointers. You can erase your length information from the type. This was an intentional decision. > Strings are the only data structure that assume there will be a NULL at end. Which is why almost every string API has a version that allows you to specify the maximum length. The fact that you can use a NUL doesn't mean you have to. Which is why the concept of "sentinel values" is broadly used in many types of applications you haven't considered here.
- AlienRobot 4mo ago>The problem now doubles with the introduction of UTF-8. Your string size is in bytes and you need to track characters separately. That isn't really a problem. The problem with null-terminated strings is specifically what happens when you reach the end of the allocated array and there ISN'T a NULL character. Every string function is designed to keep going until it finds the NULL character, so if a hacker gets rid of the NULL character, he can exploit pretty much any standard string manipulation function being used elsewhere in the program to manipulate whatever memory comes AFTER the string data structure. No other data structure works like this. You can't mess this up in an array, because no function that manipulates arrays is just going to keep going until there is a null. That would be stupid because it would require users of the function to add a NULL to the end of their arrays before passing it to the function, so instead we just pass the size of the array to everything. Strings are the only data structure that assume there will be a NULL at end. By the way, I read once that if you use UTF-32 every code point will be 4 bytes, constantly, but even then a single code point isn't necessarily a single character. Text is just complicated.
- msla 4mo agoIn addition to having to pick a size for the length counter and then, later, having to differentiate between lengths in bytes, codepoints, and glyphs, you can't subdivide a Pascal string using pointer arithmetic. To pass just the end of a string into a function, you have to either copy the tail of one Pascal-style string to another with a smaller size value, or your string has to be a struct with an integer and a pointer to the actual data instead of just an integer stuck on the beginning of the string. The first is a lot of copying in some cases, the second raises the specter of structs with invalid pointers. That's not to mention the potential problems that would cause with caches.
- estebank 4mo agoThe third option is to have a variable width length: the top most bit signals whether the next byte corresponds to the length or to the start of the string.
- cornholio 4mo agoYou can have a universal variable length field, for example 2 bytes for strings < 32768, then four bytes, 8 bytes etc. On the critical short string path, it costs just a single bit test. The glyph vs byte issues need to be dealt with in both formats. The subdivision issue is a good perspective, but i would argue the performance impact of cloning substrings is dwarfed by the redundant full string reads to find length.
- lelanthran 4mo ago> You can have a universal variable length field, for example 2 bytes for strings < 32768, then four bytes, 8 bytes etc. To hold the length of a string, I'd do something similar to unicode: 7-bits for size + 1-bit for continuation, then 15 bits for size + 1 bit for continuation, then 23-bits for size + 1 bit for continuation, etc. Or maybe even do it exactly the same as unicode: 0XXX XXXX -> length of string is in those 7 bits 1XXX XXXX XXXX XXXX -> length of string is in those 7+8 bits 11XX XXXX XXXX XXXX XXXX XXXX-> length of string is in those 6+8+8 bits ... > On the critical short string path, it costs just a single bit test. A few more clock cycles compared to NULL-termination, although my alternatives above require even more clock cycles. If the hardware had instructions for sentinel values, things would be easier (Like how DOS calls used '$' termination for strings) and safer. Load a sentinel byte into a register and have dedicated copy and compare instructions that take each two addresses (src and dst) and copies (or compares) src/dst until the terminator is reached (with copy copying the sentinel as well). Considering that sentinel values are needed so often, and are so useful, it's surprising that this is not in any ISA. What we have now is kludgy workarounds in the HLL for this. It's hard to blame the HLL, because some workaround has to be implemented.
- bsder 4mo agoZero terminated string is a special case of sentinel value termination. And sentinel value terminations make a lot of sense when you have punch cards and fixed length records that you need to carve into pieces. Nobody expected any decisions they were making in the 1960s and 1970s to have any bearing on computing a half-century later. They all expected to have their mistakes long papered over by smarter people at some point. But we ALL make the mistake of underestimating inertia.
- fragmede 4mo agocompared to Von Newman versus Harvard architecture for LLMs? I think that's a far bigger mistake.
- pjc50 4mo agoNeumann, and .. what? In what way?
- fragmede 4mo agoPrompt injection only works because there isn't two streams of input to give to the LLM. Von Neumann being the architecture with a single shared memory for both data and instructions. If there were a clean way for the LLM model to distinguish between system messages vs user messages, we wouldn't have that problem.
- amomchilov 4mo agoI don’t know how you could keep the two isolated, without drastically dropping up the utility of LLMs. Part of their wonder is how they can behave differently depending on the data they’re working with. We like that feature when the data is the “good stuff” (docs, compiler messages, etc.), but how you tell that apart from “bad stuff” (prompt injection on official-seeming pages). We basically expose LLMs to the same social-engineering vulnerabilities that humans have.
- layer8 4mo agoAlmost as bad as newline-terminated lines. ;)
- sourcegrift 4mo agoWhat's bas about them and what are the alternatives, genuinely curious since never seen them spoken of
- smackeyacky 4mo agoZero terminated strings were the basis for an awful lot of useful software. Calling them the biggest mistake in computing is a bit OTT. I haven’t programmed anything Pascal related for 30+ years but I dimly remember thinking at the time that I wished the string system wasn’t so hard to use.
- asdfasgasdgasdg 4mo agoThat useful software would not have been less useful if the strings in it were represented as size + buf.
- crackez 4mo agoOh really? Have you tried to rewrite anything to put your theory to the test? I don't think it's as straight forward as you think it is...
- smackeyacky 4mo agoExactly. The pascal I used had no way to dynamically allocate a string they were all fixed at compile time. That really sucked.
- ComputerGuru 4mo agoThat argument isn’t valid. The argument would be “this string design enabled a whole lot of useful software” but that’s a different matter. (And it could very well be the case.)
- zzrrt 4mo agoLead was the basis for an awful lot of useful gasoline. Doesn't mean it was the only solution or the best one.
- JdeBP 4mo agoA more accurate re-phrased version of the original is that they are the biggest mistake in the C language. * https://news.ycombinator.com/item?id=48614913 https://news.ycombinator.com/item?id=48614913 * https://news.ycombinator.com/item?id=24454369 https://news.ycombinator.com/item?id=24454369 * https://news.ycombinator.com/item?id=1014533 https://news.ycombinator.com/item?id=1014533
- dmazzoni 4mo ago255 characters ought to be enough for everybody, right?
- RetroTechie 4mo agoYou mean bytes.. we have multi-byte characters now.
- BobbyTables2 4mo agoPartly agree but there would have been squabbling on the data type of the size, unless it was variable length. The latter would have had other issues too. For a while, 16bit would probably have seemed too extravagant. Now 32bit would probably seem too small. For a “strongly typed” language, C is pretty damn loose where would have mattered.
- poly2it 4mo agoNo, there would not have been and this is most likely not the reason. size_t exists for precisely this use case. It has existed since C89.
- DarkUranium 4mo agoI like the D approach where arrays are just `struct { size_t length; T* ptr; }` internally --- and strings are just arrays of `immutable(char)`. It has a big advantage over the Pascal approach in that you can do zero-copy slicing, since the length is separate from the actual data. And `size_t` makes perfect sense for the length here. If your strings are longer than the address space (which `size_t` technically isn't, but is practically very strongly correlated to it), then you're going to have a problem regardless of the number of bits for the length anyway.
- astrobe_ 4mo agoThis only makes a difference in terms of memory size, not in terms of speed, because for decades processors and compilers have been optimized for moving bytes around. But one would note that in order to gain memory for this particular case of slicing, one introduces 2 extra words (size and pointer) for every other cases. Like perhaps the second most common string operation, concatenation. In those other cases, the benefit is slightly negative. I've had extensive experience with "counted strings" because I implemented a bunch of Forth interpreters which also uses this scheme. Including the common trick of using counted and zero-terminated strings, which is the worst of both worlds in the end. Forth is the kind of language that quickly show you how bad your choices are. I eventually dropped all that and adopted ASCIIZ strings because they are generally more efficient (if you pay attention to the strlen() performance pitfalls) and having a dead simple interface with the rest of the world (OS, libraries) is more valuable.
- mikewarot 4mo ago[dead]
- Conscat 4mo agoClang and GCC both let you use Pascal strings in C if you would like (with `\p`). But Pascal strings aren't that useful today because the maximum length is too short.
- jxbdbd 4mo agoWhy would a pascal string be any shorter than a C string? A C string is one pointer reaching all of memory, a Pascal string is two pointers reaching all of memory
- bc_programming 4mo agoA pascal string is a single byte with the length, followed by the data. Some implementations use more bytes for the length data, such as Delphi which changed over to a 4 byte prefix length, though those aren't technically Pascal strings anymore. I can't find anything about a Pascal string being two pointers?
- jll29 4mo agoIt is conceivable, for both Pascal and C, to have more than one string implementation side by side, so the developer can choose to use the best-fitting one. In C++23, variant<> permits to do what Rust's typed enums introduced (e.g. Result sum type that is either a "real" result - with result type - or an error - with error type -, each strongly typed). If you do that, a definition like class IString { /* basic string functions */ }; class MiniString : public IString {}; class CZeroTerminatedString : public IString {}; class PascalString : public IString {}; class CppString : public IString {}; use String = std::variant<MiniString, CZeroTerminatedString, PascalString, CppString>; // define one type for all impl. permits to define string functions that operate over the sum type String, and which use the methods defined in the interface IString, and which then work for all string implementations. The developer can then pick the most suitable implementation, i.e. CMiniString for very, very short strings (that fit into 64 bits, so approx. <= 8 UTF-8 characters), CZeroTerminatedString (for char *co = "test\n"; zero-terminated old style C strings), CPascalStrings for strings that carry a length in s[0] or as a struct member or class field, and CppString as a wrapper for the C++ std::string that implements IString. Sum types are a type-safe and memory-preserving way to do what in the older days was sometimes implemented using a "union {}" (which was not type-safe).
- lelanthran 4mo ago> the zero terminated string is I think is computing's biggest mistake. No. They had trade-offs to make, and sentinel-based sequences are a needed thing, even outside of strings. The mistake was that ISAs never looked at what HLL needed, then add the necessary instructions (I posted more about this below). Even NULL is not a big mistake, when looked at in context of the time in which it was developed.
- layer8 4mo agoThere is a middle ground that Visual Basic (and then COM) took, with the BSTR type: It’s still a pointer to a zero-terminated char array, but there is a length field immediately preceding the first pointed-to byte. This is still compatible with a C string (assuming no embedded null characters), but BSTR-typed functions can take advantage of the length value.
- tremon 4mo ago> This is still compatible with a C string Strictly speaking, it's not alignment compatible from CString to BSTR unless you declare all strings to be at most 255 characters or the cpu architecture doesn't require aligned access for multi-byte words (like x86). The BSTR alignment must match the alignment of the length word, meaning you can't convert a randomly-aligned C string to BSTR by simply attaching a prefix in-place. Also, having the length embedded in the value rather than in the pointer makes it impossible to create BSTR (sub)slices without performing a memcpy. Fat pointers do not have this restriction.
- layer8 4mo agoA BSTR object is compatible with functions expecting a C string. The other direction obviously never holds, unless the C string is a BSTR to start with. Yes, there is a trade-off between slices using the same format and having compatibility with C strings. Hence “middle ground”. You can still use a string-slice type on top of BSTR, it just would be a separate additional type. Note that languages like Java also don’t have a singular type for strings and string slices.
- jiggawatts 4mo agoThese are great for "data smuggling" attacks where one layer of code assumes the length is 'x' and another layer assumes it is 'y'. It makes hybrids like this very dangerous for anything even remotely security-adjacent, such as roles, tokens, etc. This kind of thing caused the CVE-2009-2408 and CVE-2009-2510 "Null Truncation in X.509 Common Name Vulnerability."
- badsectoracula 4mo ago
- sourcegrift 4mo agoRust has "pascal style strings" (quotes because the concept is slightly different) so it's not a done deal