r/cprogramming • u/die-Banane • May 05 '26
How to do strings properly?
I just started learning C and I often read on the internet that it is bad practice to use null terminated strings, so my question is what should I do instead?
30
Upvotes
56
u/flyingron May 05 '26
You need to read better things. Null-terminated strings are the standard way of handling strings in C (which lacks the concept of a string type). Your other options would require you to write your own library of string manipulation packages. Every standard C library function that wants a string, takes a null-terminated one.
That being said, you need to be careful about what you are doing... don't write over string literals, when doing concatenations or insertions, be sure that you're doing so in a sufficiently large allocation, etc...
6
u/v_maria May 05 '26
Its just what c gives you so its what you will use
5
u/Willsxyz May 05 '26
One of the great things about programming in C is that you get to break those rules you read about on the internet. Not only can you use null-terminated string. You also get to use pointer arithmetic and goto.
3
u/Interesting_Buy_3969 May 05 '26 edited May 13 '26
Just always remain very careful. And no, it is not a "poor way to operate with strings" or something, it's the standard approach and you shouldn't avoid it.
First of all, everyone programming in C should know that a C string is represented as an array of characters (typically 1-byte width) in memory that ends with zero character (literally just 0). A few (maybe interesting or useful) facts about C strings:
const char*, not justchar*!). So you can do this:char* some_func() { const char static_cstring[] = "astolfo"; // or also could have declared in array-like style: // const char static_cstring[] = {'a', 's', 't', 'o', 'l', 'f', 'o', 0}; // the last character must be zeroed manually because // double quotes guarantee it, but raw array of chars does not. return static_cstring; }Despite that it seems like UB (returning a pointer to local variable), actually it's absolutely correct because
"astolfo"will live always live in your output binary's statical readonly data section (typically.rodata).""meansNULL. (Maybe useful.)strcmp,strcpyand other C standard functions to handle string operations. They're supported almost everywhere; yet if you use GCC / Clang, they're available even in freestanding mode (__builtin_strcmp,__builtin_strcpy,__builtin_strncpy, etc.).int x = 'a';- x here will be initialised with the ASCII code of the character 'a', whereasint x = "a"; will fail to compile.3
u/Low_Lawyer_5684 May 05 '26
Don't trust everything you read on the Internet. Zero-terminated strings are simple. Yes, they have disadvantages but simplicity beats it all. Sometimes, when we need higher speeds we can create our hybrid strings - still null-terminated but with str[-1] containing total string length, so it is still C-string but with its length precomputed.
5
u/Maleficent_Memory831 May 05 '26
Use null terminated strings. Best advice. Whoever said it was bad practice is wrong, or is trying to force you to a different language.
2
u/knouqs May 05 '26
I'll join the ranks of people who say that null-terminated strings are not just the recommended way to handle strings, it is the way that the clib library functions found in string.h uses this approach. It's a really simple, easy way to handle strings.
So, why the bad reputation? If you do a strcpy into a too-small buffer, you have a buffer overrun which can cause all sorts of nasty behaviors. This is when you learn how to really handle memory in C correctly, and really, it becomes very efficient to handle strings in memory as you have some really low-level control over the string buffers.
2
u/Intelligent_Part101 May 05 '26 edited May 05 '26
Ugh. No other language does strings like C. C doesn't even have a proper string type; it's just a pointer to the first character and a loose promise it will end in a zero byte.
If you do any string manipulation at all, use or define a little string library. The library should give you a way to access the raw string data (for interoperability with existing C string functions) as a pointer to a null terminated sequence of character bytes. The improved C string type should also store the length of the string. This is important.
A struct containing those 2 things as fields can be the basis of your string type. Then define functions to join, take substring, etc., because the ones in the C standard library are just dangerously designed trash.
2
u/Revolutionary_Ad7262 May 05 '26
String with a length (so
char* + int) is generally a better idea, which is a standard way in other languagesOn the other hand it is like going to someones party and responding to each discussion with
akshually. A lot of existing code in C as well in the standard lib depends on null terminated strings, so you need to be careful2
u/air_thing May 05 '26
You don't have much choice but to use null terminated strings, that's what strings are in C. If you're working with a lot of strings you might want to reconsider if you want to use C for the problem. There are string libraries/wrappers available. You could make your own if you want. But you should know it is one of C's weak points and to proceed with caution.
3
u/joejawor May 05 '26
Nothing wrong with null terminated strings. You can also use any other character that doesn't appears in your strings, If you want to get fancy you can make the first character hold the length of the string.
1
u/flatfinger May 05 '26
Code which needs to assemble strings needs to keep track of a few things: the starting address of a buffer, the buffer's capacity, the length of the string currently in the buffer, and the action to take if a string won't fit in the buffer (which could include replacing the buffer with a bigger one, truncating the string, or triggering an error).
For many tasks, it will make sense to hard-code some of those things. One could, for example, have a named fixed-sized character array and decide that any attempt to assemble strings longer than that will simply keep as much as will fit and discard anything else. If one does that, one could hard-code everything except the string's current length. Alternatively, one could pass around structures that contain all of the above information, e.g.
If one doesn't know in advance the length of strings that will be required, but they're not likely to exceed e.g. 200 characters, one could create a structure like the above which initially points to a char[200], but have its action procedure respond to requests to increase length by calling free() on text if it flags is set, then setting flags and calling malloc() to create a new buffer. If there are separate actions for "Set string to its final length" versus "Set string length and anticipate further expansion", then the amount of storage allocated in the former scenario could precisely equal what's requested, while in the latter scenario code could leave space for further expansion.
Incidentally, I use
unsignedrather thansize_tfor lengths because texts longer thanUINT_MAXshould be handled via means that would not require them to be stored as a sequence of consecutive bytes, and that would be true both on platforms where UINT_MAX is 65535 and those where it would be 4294967295.1
u/KilroyKSmith May 05 '26
Strings in ‘C’ are fine, as are most of the standard string functions. But:
That said, doing strings in ‘C’ is like being given piles of iron ore, cement, and sand and deciding to build a skyscraper. It can be done, but a better starting point (for example, Python) would likely get things done sooner.
1
u/ifknot May 05 '26
C is a product of its time and the computational constraints under which it was forged there is elegance in its form but danger in its function much like a scalpel use it wisely and with understanding avoid the ad hominem or at least those prone to logical fallacy
1
u/BusEquivalent9605 May 05 '26
literally no one knows
1
u/SmokeMuch7356 May 05 '26
There's not a whole lot else you can use in C. As far as C is concerned a string is just a sequence of character values including a 0-valued terminator. That's what all the standard library routines expect (not just string handling routines, but I/O routines like
printf/scanf/fgets/fputsas well). Strings (including string literals) must be stored in arrays of character type, and the array must be large enough to include the terminator.is not a string (no terminator), while
is.
There's no built-in
stringdata type as such; there's no metadata for length or encoding or anything else that's associated with them.You can certainly create your own
stringtype with your own API, but under the hood it's going to be null-terminated sequences of characters.What will trip you up (because it trips everybody up) is how array expressions "decay" to pointer expressions. If you create an array of
charlike:what you have in memory looks something like
(Addresses are just for illustration.) The object named
foois not a pointer; there's no pointer value stored as part of the array. However, when the expressionfooappears in a statement (such as arithmetic expression likefoo + 1or a subscript expression likefoo[i]or as a function argument likestrlen( foo )) or as an initializer in a declaration (such aschar *p = foo), then that expression is converted from type "4-element array ofchar" to "pointer tochar" and the value of the expression is the address of the first element (in this case,0x8000).This is why all the
str*functions in the standard library takechar *arguments, notchar [N]arguments; all they are receiving is a pointer to the first element.Some third-party libraries create a
stringtype that's just an alias ofchar *. Most of the time when we're working with strings we're dealing withchar *expressions, so this isn't unreasonable. But achar *is not a string in the C sense.1
u/bateman34 May 05 '26
The alternative is length based strings:
These are much nicer when you do a lot of slicing because you don't have to do an allocation for every slice eg think about if you want to split a string at every space. They are a lot less painful than null terminated.
1
u/SimoneMicu May 05 '26
# What are the alternatives?
Null terminated string are default string in C (them in the interop of the computers).
The issue is passing out malicious code who overrides stack of your program and could change instructions executed by ypur code.
There are multiple approaches to solve this issue.
First is the 'n' version of libc string function, allocate a buffer, do string operations like copy, len, concatenate then pass to it max size expected. This is the best solution as general purpose.
Popular alternative is to build a structure around, you can have a slice where you hold length of the string and the first character, slice don't have string ownership, this consent reference into a larger text (to print a fixed size string you just do `printf("%.*s", len, str);`)
Another good one is covered by sds of antirex where you stack multiple concepts, you have memory ownership and lenght, then you have either reference counter, you pay 8 byte of extra data (uint32_t is clearly enough for both) to have safe shared string and safe size upfront.
All of this possible views for a string come to a tradeoff, zero overhead and ubiquitous coverage for risk of malicious use (use always the n versione for external input value or cutoff with `'\0'` at the end of the buffer and copy only in the buffer size the input). Slice make simple complementary reference without warranty of reference quoted, SDS pay an overhead but give deterministic resource lifetime in shared environment and store length upfront with zero computation time (useful for message passing and allocation).
Most of the time these two strut should use internally the null terminated c-style string because this make easy to use other libraries and have good sense.
# Why are demonized?
If you have a socket listening or an user input in a stack-alloated buffer, if you don't treat it with attention you expose to buffer overflow attacks your code.
The solution is really simple, if we have a simple buffer like `char buf[1024];`, you never use `gets(&buf)` because deprecated and don't give option to protect, in a socket you can `recv(socket, &buf, 1024, ...)` and include protection, but a good idea is always to `buf[1023] = '\0'` or `buf[1023] = 0` to avoid leaking any kind of data if printed after, either scanf require some attention in the return value or using the seen format of `scanf("%.*s", 1024, &buf)`.
People apparently forget enough time these safety behaviors on external strings to make some other describe them as dangerous. The only concrete benefit on other implementation relays on length as value passed upfront, avoiding double counting of the string, specifically for long strings (like internet protocol's messages)
1
u/DawnOnTheEdge May 06 '26 edited May 06 '26
I suggest you create a string-slice type, something like
This helps prevent buffer overruns by making sure the program always remembers the string length. It can avoid extra calls to
strlen(). It can represent substrings without modifying the string. Functions can return slices and be chained together much more easily than if string pointers and lengths were stored in separate variables.If you can design your API around it, you can pass in and return these objects. Otherwise, you will write a sort of constructor like
You will often know a maximum size and use
strnlen(). Since this is C, you have to track which pointer owns dynamic memory manually, but you can often chain a function like this so it converts the return value of a function likestrdup()into an object that owns the memory.You then glue this data structure to other code with something like
1
u/Living_Fig_6386 May 06 '26
I don't know what you are reading, but it's perhaps not a good resource. In C, you use null-terminated strings because that's what the C library functions expect. It's a very necessary practice never to treat random data in buffers / arrays as if they were null-terminated strings without first assuring that they are - so caution is called for. However, you generally use null-terminated strings.
1
u/imaami May 06 '26
Here's a simple local string object with a trick that allows storing the string length while always being null-terminated. Note that the object is always a fixed 256 bytes long; it's meant for local short strings only.
1
u/grimvian May 06 '26
Null terminated string is very C'ish.
1
u/Individual-Tie-6064 May 07 '26
Know your data. I’ve worked on projects where the stream of data contained nulls. It broke the app. Essentially all of the STDLIB string functions were useless.
1
u/SymbolicDom May 08 '26
It's a big problem, the standard way to do it in c are null terminated strings. It makes it hard to avod nasty buffer overflow buggs. You also get two dufferent length, needed buffer length and character length. The way most other languages do it is to represent strings with an struct with an int for the length an a pointer to the array. The extra annoying thing is that when you convert an normal string to an null terminated string you usually need to allocate an new area an copy over the data to get the space for the null terminator. So if performance are paramount you kind of get forced into null terminated strings.
1
u/duane11583 May 05 '26
The internet is full of penis enlarge by solutions and do you believe they are true also?
They are bullshit and wrong
Null terminated strings work well and they are like a knife you can do good work with a knife or cut your dick/boobs you just need to use the tool correctly