3 ms·
The difficulty of dealing with strings in C is an specific instance the larger problem of missing the key idea that an array shouldn't be just memory, it should
by david-gpu 7y ago
The difficulty of dealing with strings in C is an specific instance the larger problem of missing the key idea that an array shouldn't be just memory, it should be memory plus dimensions.
C would have been a much better language if its arrays/buffers were always sized. It would have made its stdlib and application APIs much safer and would even have enabled having bounds checking as an optional compilation flag.
- thrower123 7y agoPascal-strings were not uncommon in C at one point, rather than null-terminated strings. They lost, but in a sense, they didn't, since all the string-manipulation functions we use nowadays take a length parameter anyways.
- zoomablemind 7y agoThe notion was that strings would be consumed fully, thus the starting pointer could be used for iteration, and null char is a natural end condition. Here it is, saving an int and cycles for tracking length. It's just coding in such way appears to be too low-level. Pointer in programmer's hand became akin to neuro-surgeon's scalpel... casually performing surgery often on 'self' and with shaky hands. Sure, take this length to limit potential damage.
- megous 7y agoPeople usually add their own or use existing libraries for strings with bounds. All I'd argue is that it's somewhat annoying that C standard library donesn't have these, so there are too many variants of basically the same thing out there, because most programs benefit from having strings with (unchecked) bounds.
- david-gpu 7y agoBounded arrays and array sliced should not be part of the stdlib, they should be a primitive type of the language. Only then you can have automatic bounds checking for every array indexing operation.
- goatinaboat 7y agoIt is not entirely missing that idea, since what you malloc() must be aware of its own size, even if that’s not usually something you get access to as a programmer. One way I’ve seen this done is you malloc() 30 bytes, it allocates 34 and gives you a pointer to 4, and bytes 0-3 hold internal information for the malloc/free implementation.