Bug: Initial allocation not cleared to zero

Your initial allocation of sb->mem uses malloc instead of calloc, so its contents are uninitialized. If you then append a few characters and call sb_as_string(), you will get back a string that is not properly terminated. You should use calloc instead.

Minor bug

If your call to realloc fails, your buffer will be incorrect because it will no longer be null terminated (you just appended a character to the last spot). You should either rewrite a '\0' to the end of the buffer if realloc fails, or do the realloc before you append the character.

Argument check

When creating a string buffer, you should handle the case where init_cap is passed in as 0. You can set it to some default value in that case. Right now, an initial capacity of 0 will cause a crash down the line because your append function will append to a zero length buffer without ever reallocating.

Usability

I would much prefer an append function that took a string argument instead of a character argument. I'm not sure that I would ever need to append one character at a time.

Also, it might be nice to have a to_string type function that returns the string but also frees the stringbuilder. The way you currently have it, you can retrieve the string, but if you subsequently free the stringbuilder it will also free the string you just retrieved. That makes it difficult to use the string because its lifetime is tied to the lifetime of the stringbuilder.

Answer from JS1 on Stack Exchange
🌐
GitHub
github.com › cavaliercoder › c-stringbuilder
GitHub - cavaliercoder/c-stringbuilder: A simple StringBuilder in C · GitHub
A concatenated output string can be generated or regenerated at any point in O(n) - where n is the total length of all appended string fragments. This substancially defeats traditional, iterative concatentation which runs in O(n^2). This implementation is not thread-safe, uses unbounded iteration (for now) and does not (ever) offer any form of input sanitization. // create an empty string builder StringBuilder *sb = sb_create(); char *str = NULL; // append some strings sb_appendf(sb, "What is your name?\n -> %s\n\n", "Sir Lancelot, of Camelot"); sb_appendf(sb, "What is your quest?\n -> %s\n\n", "To seek the Holy Grail"); sb_appendf(sb, "What is your favorite color?\n -> %s\n\n", "Blue"); sb_append(sb, "Right, off you go"); // print str = sb_concat(sb); puts(str); // clean up free(str); sb_free(sb);
Author: cavaliercoder
🌐
Reddit
reddit.com › r/c_programming › string builders in c
r/C_Programming on Reddit: String builders in C
June 3, 2023 -

I've written a bunch of code that prints values of various different types which works great but rather than printing to stdout I'd like to capture the result in a big string. In other languages this would be achieved by appending to a string builder or appending strings to an array and then concatenating them all. Is there an idiomatic way to do this in vanilla C? If not, what library would you recommend (M1/M2 Mac OS and Raspberry Pi)?

How do strings work in C Oct 15, 2025
r/C_Programming
10mo ago
string implementation Aug 5, 2023
r/C_Programming
3y ago
str: yet another string library for C language. Oct 25, 2024
r/C_Programming
last yr.
More results from reddit.com
Discussions

strings - StringBuilder in C - Code Review Stack Exchange
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Lots of languages have something that lets you build up a dynamically-sized string with minimal overhead. C doesn't, and I found myself using code that did that manually in a couple of places, so I packaged it into a class. Note that I've only implemented functionality I'm using. #ifndef CONCATEN_STRINGBUILDER... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
February 14, 2017
c# - StringBuilder: how to get the final String? - Stack Overflow
Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string. How can I get the string? More on stackoverflow.com
🌐 stackoverflow.com
How to convert from string to stringbuilder? - Post.Byes - Bytes
This topic is closed. ... When having a string that is defined as a stringbuilder it can be converted to a string by this: StringbuilderTe xt.ToString(); But what about the otherway round? More on post.bytes.com
🌐 post.bytes.com
stringbuilder to string[]
It may not display this or other websites correctly. You should upgrade or use an alternative browser. ... Not open for further replies. ... I am using the kernel function to read dot-ini sections and section values. The function ReadPrivateProfileSection returns a 'stringbuilder' value which is a series of strings ... More on tek-tips.com
🌐 tek-tips.com
3
0
October 12, 2013
🌐
Lua Ternary
nachtimwald.com › posts › efficient c string builder
Efficient C String Builder | John's Blog
February 27, 2017 - To make things easier on myself I wrote a simple string builder in C. ... #ifndef __STR_BUILDER_H__ #define __STR_BUILDER_H__ #include <stddef.h> /*! addtogroup str_builder String Builder * * A mutable string of characters used to dynamically build a string. * * @{ */ struct str_builder; typedef struct str_builder str_builder_t; /* - - - - */ /*! Create a str builder.
Top answer
1 of 3
7

Bug: Initial allocation not cleared to zero

Your initial allocation of sb->mem uses malloc instead of calloc, so its contents are uninitialized. If you then append a few characters and call sb_as_string(), you will get back a string that is not properly terminated. You should use calloc instead.

Minor bug

If your call to realloc fails, your buffer will be incorrect because it will no longer be null terminated (you just appended a character to the last spot). You should either rewrite a '\0' to the end of the buffer if realloc fails, or do the realloc before you append the character.

Argument check

When creating a string buffer, you should handle the case where init_cap is passed in as 0. You can set it to some default value in that case. Right now, an initial capacity of 0 will cause a crash down the line because your append function will append to a zero length buffer without ever reallocating.

Usability

I would much prefer an append function that took a string argument instead of a character argument. I'm not sure that I would ever need to append one character at a time.

Also, it might be nice to have a to_string type function that returns the string but also frees the stringbuilder. The way you currently have it, you can retrieve the string, but if you subsequently free the stringbuilder it will also free the string you just retrieved. That makes it difficult to use the string because its lifetime is tied to the lifetime of the stringbuilder.

2 of 3
3

To be more comprehensive, the line in sb_append():

memset(new_mem + to->cap, 0, to->cap);

should become:

memset(new_mem + to->cap, 0, (to->cap) * (LOAD_FACTOR - 1));

That matters when LOAD_FACTOR is set to something greater than 2.

thanks for sharing this code.

🌐
GitHub
github.com › YeGoRenji › C_StringBuilder
GitHub - YeGoRenji/C_StringBuilder: This is a simple stringbuilder for C
This is a simple stringbuilder for C. Contribute to YeGoRenji/C_StringBuilder development by creating an account on GitHub.
Author: YeGoRenji
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › base-types › stringbuilder
Using the StringBuilder Class in .NET - .NET | Microsoft Learn
In situations where you need to ... String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object....
🌐
TutorialsPoint
tutorialspoint.com › stringbuilder-tostring-method-in-chash
StringBuilder.ToString() Method in C#
The StringBuilder.ToString() method in C# is used to convert the value of a StringBuilder to a String. Syntax The syntax is as follows − public override string ToString (); public string ToStr
🌐
GeeksforGeeks
geeksforgeeks.org › stringbuilder-tostring-method-in-c-sharp
StringBuilder.ToString Method in C# - GeeksforGeeks
January 29, 2019 - This method is used to converts the value of this instance to a String. A new String object is created and initialized to get the character sequence from this StringBuilder object and then String is returned by ToString().
🌐
Codefinity
codefinity.com › courses › v2 › 8204075c-f832-4cb9-88b1-4e24e74ebdcb › 0d8ac683-ca3e-4b9a-b780-d8305391b86f › 508cbff8-983a-46e7-8b76-da5ad5807636
Learn Challenge: StringBuilder | String
Inside the parentheses, we can also pass a string value, and our StringBuilder variable will hold that value: ... To print our value to the console, we need to use one of the StringBuilder methods. It's the toString() method, which converts ...
🌐
Post.Byes
post.bytes.com › home › forum › topic › c sharp
How to convert from string to stringbuilder? - Post.Byes - Bytes
This topic is closed. ... When having a string that is defined as a stringbuilder it can be converted to a string by this: StringbuilderTe xt.ToString(); But what about the otherway round?
🌐
Dot Net Perls
dotnetperls.com › stringbuilder-tostring
C# - StringBuilder ToString: Get String - Dot Net Perls
ToString on StringBuilder returns a string. It internally converts the character buffer of the StringBuilder into a string object.
🌐
Tutorial Teacher
tutorialsteacher.com › csharp › csharp-stringbuilder
C# StringBuilder
Use the ToString() method to retrieve a string from the StringBuilder object.
🌐
ByteHide
bytehide.com › blog › stringbuilder in c# – basic & advanced tips
StringBuilder in C# - Basic & Advanced Tips (2026)
December 21, 2023 - StringBuilder in C#, my friend, is a mutable sequence of characters. It’s a fascinating class in the .NET Framework, fast and efficient in situations where you need to perform repeated modifications to a string.
🌐
Tek-Tips
tek-tips.com › home › forums › software › programmers › languages › c# (c sharp): microsoft
stringbuilder to string[] | Tek-Tips
October 12, 2013 - It may not display this or other websites correctly. You should upgrade or use an alternative browser. ... Not open for further replies. ... I am using the kernel function to read dot-ini sections and section values. The function ReadPrivateProfileSection returns a 'stringbuilder' value which is a series of strings representing the key=value items of the section as strings (null terminated) and terminated with a final null.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › StringBuilder.html
StringBuilder (Java Platform SE 8 )
July 21, 2026 - This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type.
🌐
Codebuns
codebuns.com › home › c# › c# stringbuilder
C# StringBuilder (Step-By-Step Tutorial)
August 27, 2024 - Constructor Signature: StringBuilder(string value, int capacity); ... Once you are done with string manipulation, than call ToString method to convert StringBuilder object into a regular string.
🌐
Codefinity
codefinity.com › blog › What-is-the-StringBuilder-in-C-sharp
What is the StringBuilder in C#
When you manipulate strings using the standard concatenation operator (+), a new string object is created for each concatenation operation. This can lead to performance issues, especially when dealing with large strings or a large number of concatenations. StringBuilder, on the other hand, uses a resizable buffer to store the string content.