2 ms·
People have been complaining for years now about C stile strings (that have been widely used for decades now). But nobody ever did anything about it ? There ha
by wahern 10y ago
People have been complaining for years now about C stile strings (that have been widely used for decades now). But nobody ever did anything about it ?
There have been many efforts (http://www.and.org/vstr/comparison http://www.and.org/vstr/comparison), but ultimately they all failed to find widespread adoption because they're solving the wrong problem.
For any non-trivial data munging operation experienced C programmers quickly ditch C strings in favor of vectors.
The simplest approach employs a simple pointer and length (or boundary) tuple; i.e. a vector. You can get fancy by wrapping them in a struct, but even that isn't necessary and, especially wrt API design, often needlessly forces interface users to create temporary "slice" objects with an annoying type peculiar to the interface. Newer languages offer nicer interfaces for slices, but simple pointers are hard to beat in terms of simplicity and usability. (The only problem with simple pointer derivation and manipulation a la C is that they're difficult for a compiler to both verify the correct use of _and_ to aggressively optimize. You must choose one or the other. Requiring the user to use specialized, compiler sanctioned primitive aggregate types in languages like Rust is a way to meet the compiler half-way.)
Also, for complex parsing tasks experienced C programmers will often code a straight-up state machine, or leverage a parser generator. In both cases C-style NUL terminated strings aren't even visible in the rearview mirror.
IME, I've found that parsing of data is one of the areas where C excels. And by parsing I don't mean attacking data with regular expressions. Likewise, for creating complex data structures like graphs C excels, especially when you want to employ intrusive data structure patterns for efficiency and clarity. Pointers are wonderful abstractions that way.
There are a lot of difficulties with C, particularly regarding memory management. But string processing is not one of them, except for programmers for whom at that moment parsing is synonymous with crude hacks using regular expressions or the limited interfaces for C-style strings. It's self-inflicted. The solution doesn't require a complex framework. Addressing the issue merely requires reframing the task. Fortunately, when reframing is too burdensome, for quick and dirty string hacking there are plenty of alternative languages.