Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.

Here's a function I wrote some time ago. Note it's intended only for text input.

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
            ch = 0;

        /* Check if we need to expand. */
        if (size <= index) {
            size += CHUNK;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        /* Actually store the thing. */
        line[index++] = ch;
    }

    return line;
}
Answer from cnicutar on Stack Overflow
🌐
GitHub
github.com › antirez › sds
GitHub - antirez/sds: Simple Dynamic Strings library for C · GitHub
Because of its many years life ... level string library. Normally dynamic string libraries for C are implemented using a structure that defines the string....
Starred by 5.4K users
Forked by 501 users
Languages   C 99.6% | Makefile 0.4%
Discussions

How to read input of a string with an indefinite size using Dynamic Memory Allocation?
read chars one at a time and realloc when needed More on reddit.com
🌐 r/C_Programming
9
7
June 21, 2022
Dynamic Strings in C - Code Review Stack Exchange
I wrote this code for dynamic strings and would like to know what mistakes I've made. It's just a struct that gets filled on the first call to ds_allocate and freed on the first call to ds_free. I... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 28, 2013
How to dynamically allocate an array and add strings to it? (In C)
Important question: Do you want to return an array of characters, or an array of strings? More on reddit.com
🌐 r/learnprogramming
8
1
February 17, 2022
what is the point of dynamic allocation in c? (plus dont get triggered. please explain why im wrong)
The two big benefits you get from dynamic allocation are: No size limit on how much you can get from the heap (I believe this is dependent on the OS and your memory). The Stack is limited to I believe 8mb at most. Data allocated on the heap doesn't "die" when leaving the local scope. More on reddit.com
🌐 r/C_Programming
38
7
August 8, 2022
🌐
RIT
se.rit.edu › ~swen-250 › slides › instructor-specific › Rabb › C › 06-C-Memory-Alloc-Strings.pdf pdf
Personal Software Engineering Memory Management in C (Dynamic Strings)
... Frees the memory assigned to ptr. ... The space must have been allocated by malloc. ... Can slowly consume memory if not careful. ... Caller now "owns" this space. ... The constant strings have preallocated static storage. The dynamic strings (p1 and p2) are in dynamically allocated space.
🌐
Locklessinc
locklessinc.com › articles › dynamic_cstrings
Dynamic Strings in C
Strings in C are defined as a stream of contiguous bytes, terminated by a byte with the value zero. The C standard library has many functions that deal with this type of string, but they suffer from one major problem. The definition of a C string does not contain the size of the memory allocated ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › how-to-create-a-dynamic-array-of-strings-in-c
How to Create a Dynamic Array of Strings in C? - GeeksforGeeks
July 23, 2025 - To create a dynamic array of strings in C, we can use the concept of double pointer and dynamic memory allocation. The double pointer is the pointer that stores the memory address of another pointer.
🌐
Reddit
reddit.com › r/c_programming › how to read input of a string with an indefinite size using dynamic memory allocation?
r/C_Programming on Reddit: How to read input of a string with an indefinite size using Dynamic Memory Allocation?
June 21, 2022 -

Im trying to create a program that takes a users commands and with them creates an HTML file.So for example the input could be newPar [text].And the command will be saved in a string called cmd that has a max of 10 characters.But how can I save the input that is the text of the paragraph in a string that I dont know the length of until the user has typed it?

Edit:Thank you all for the help!!Every suggestion was extremely helpful!Sorry for not answering to all of the comments and taking a while to answer or upvote the comments Unfortunately I didnt manage to finish the program before the deadline I needed to due to other problems I had with making it and not having enough time.But again thank you for helping me overcome the problem I very much appreciate it! :)

Find elsewhere
🌐
GNU
gnu.org › software › libc › manual › html_node › Dynamic-String-Input.html
Dynamic String Input (The GNU C Library)
{ char *variable, *value; if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n", &variable, &value)) { invalid_input_error (); return 0; } ...
🌐
Wikiversity
en.wikiversity.org › wiki › C_Programming › Strings
C Programming/Strings - Wikiversity
There is no string type in C. Instead we have arrays or constants, and we can use them to store sets of characters. The string "Hello World!" can be stored like in the example below · This creates an array of chars so that s[0] is 'H', s[1] is 'e', etc. In addition, because C allows us to ...
🌐
Quora
quora.com › How-do-you-properly-dynamically-allocate-a-string-C-string-pointers-memory-management-malloc-development
How to properly dynamically allocate a string (C, string, pointers, memory management, malloc, development) - Quora
Answer (1 of 4): You have 3 choices: malloc, calloc, and realloc. malloc [code ]void *malloc(size_t size);[/code] malloc gives you raw bytes of memory, uninitialized, for any kind of storage you might need. A cast is performed to a pointer type of the needed storage, and the compiler then trea...
🌐
Ubaldo Acosta Soto
ictdemy.com › c-language › dynamic-memory-allocation › dynamic-strings-and-structures-in-the-c-language
Lesson 4 - Dynamic strings and structures in the C language
We store the string from the user into the auxiliary array. The array should be long enough to carry the whole text. Depending on the length of the entered string, we then create a new dynamic string, by allocating a char array in memory. It probably won't surprise you that it's 1 character longer than we need, due to the zero character.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 113508-dynamically-allocated-strings.html
dynamically allocated strings??
March 19, 2009 - Cool. Thank you. I'll post again if I run into any problems ... char *string = malloc(sizeof(char) * 100); . . . for a string of a size of 100 characters.
Top answer
1 of 3
5

The code is generally nice, so my comments are really just picking up crumbs.

I'm not comfortable with your use of asserts to catch errors that could legitimately occur at runtime. I consider asserts to be for asserting logical impossibilities, not for catching runtime errors.

Function expand is equivalent to expand_by_at_least(ds, 1)

Long parameter names destination and source could be abbreviated dst and src with no loss.

Is giving the user a read-write (ie. non-const) pointer to the private string a good idea (functions returning char*)? And is the position returned consistent (think not - sometimes the new end of string sometimes the old).

In ds_compare (ds_compare_n), why not just return the strcmp (strncmp) of the two strings?

I don't like the loop in ds_append_cstring. A simple loop copying and checking for destination full, expanding as necessary would be simpler.

Edit: Do you mind giving me an example of what assert errors could legitimately occur at runtime?

In the context of your code, I have no problem with asserting non-null pointers, but asserting for non-zero string length seems unsafe. There are many times when a string could have a zero length but the assert says that users of your code must guarantee that it is always a design fault in their code for a nul string to pass into your functions. Not only is this unreasonable, it is is unnecessary as you can easily handle such cases. BTW don't assume that mallocing 0 is equivalent to free (it isn't) - handle a zero request by allocating at least 1 byte.

As an example of testing a logical impossibilty consider some code that does:

expected length = calculate expected length of string
allocate memory
real length = create string in memory
assert(real length = expected length)

The assert tells you whether your algorithms are consistent/correct

2 of 3
4

Overall

Your header doesn't include any function declarations so I'm not sure what your "public interface" will be but only few of your functions are static so I have to assume you intend to make all others available in which case I have to say I don't like the interface into your structure.

From the looks of it your Dynamic_String should only be manipulated through the appropriate ds_ functions yet your return the pointer to the internal storage from various functions which has the potential for the programmer screwing it up easily.

So consider carefully defining the interface into your structure and how you intend it to be used. Most of you functions should either return Dynamic_String * or an int result indicating whether or not the operation was successfully executed. When dealing with memory allocation you should always check the result.

I'd probably even go as far as making Dynamic_String opaque. Suggested interface in your header file:

typedef struct Dynamic_String Dynamic_String;

Dynamic_String* ds_allocate(size_t initial_size);
int ds_resize(Dynamic_String* ds, size_t new_size);
int ds_reserve(Dynamic_String* ds, size_t amount);
int ds_shrink(Dynamic_String* ds, size_t amount);
void ds_free(Dynamic_String* ds);

int ds_compare(const Dynamic_String* first, const Dynamic_String* second);
int ds_compare_cstr(const Dynamic_String* first, const char* second);

int ds_copy(Dynamic_String* destination, const Dynamic_String* source);
int ds_copy_cstr(Dynamic_String* destination, const char *src);

Dynamic_String* ds_duplicate(const Dynamic_String* ds);
Dynamic_String* ds_from_cstr(const char *str);

int ds_append(Dynamic_String* destination, const Dynamic_String* source);
int ds_append_cstr(Dynamic_String* destination, const char* source);

... // etc. other useful manipulation functions 

const char* ds_getcontent(Dynamic_String* ds);
char* ds_getcontent_unsafe(Dynamic_String* ds); // all bets are of

... // query function like capacity, current size, is_empty/full etc.

Technical Details

  1. ds_allocate does not check if there is already memory allocated and will simply leak if you pass in a structure which already has storage allocated. It think ds_allocate should simply allocate the structure and return it. Otherwise the programmer has to allocate the Dynamic_String structure and then call this init function which seems redundant. As user I'd prefer something along these lines:

    Dynamic_String* ds_allocate(size_t initial_size)
    {
        Dynamic_String *result = malloc(sizeof(Dynamic_string));
        if (result == NULL)
        {
            return NULL;
        }
        ...
    }
    

    Basically return NULL if any of the memory allocations fail or initial_size < 1. Provide a ds_allocate_default() if you want to give the programmer an option to just allocate an object with default size (I personally don't like these implicit "pass 0 or negative to obtain a default size allocation" implementations but YMMV).

  2. Technically the result of a pointer subtraction is ptrdiff_t and not size_t. The former is signed while the latter is unsigned. You should probably store the result of the subtraction in a local variable of type ptrdiff_t and check that it's not negative before returning it as size_t. If it's negative you apparently have hit a bug in the implementation.

  3. ds_append_cstring can be greatly simplified by using memcpy rather than copying each byte individually. It will also be much faster.

🌐
Quora
quora.com › How-do-you-initialize-a-dynamic-string-string-which-size-is-not-fixed-to-NULL-in-C
How to initialize a dynamic string (string which size is not fixed) to NULL in C - Quora
Answer: A dynamically allocated string in C is just a dynamically allocated area of memory holding all the characters of the string, terminating with an ASCII NUL (i.e. a byte set to 0). In C you refer to strings using pointers to the beginning ...
🌐
GeeksforGeeks
geeksforgeeks.org › c language › storage-for-strings-in-c
Storage for Strings in C - GeeksforGeeks
July 23, 2025 - So this kind of string should only be used when we don't want to modify the string at a later stage in the program. ... Strings are stored like other dynamically allocated things in C and can be shared among functions.
🌐
GitHub
gist.github.com › water-air-flash › fb74ab18c53c485769c2a6cd1b81f082
Dynamic string implementation for C · GitHub
Save water-air-flash/fb74ab18c53c485769c2a6cd1b81f082 to your computer and use it in GitHub Desktop. Download ZIP · Dynamic string implementation for C · Raw · main.c · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Reddit
reddit.com › r/learnprogramming › how to dynamically allocate an array and add strings to it? (in c)
r/learnprogramming on Reddit: How to dynamically allocate an array and add strings to it? (In C)
February 17, 2022 -

Okay so basically I have a function that takes in a string and counts the lowercase tokens in it. I need to make a function that then returns an array of the lowercase tokens. I would need to use malloc to allocate enough memory for such array but I don’t know how to go about doing so.

Once the array is allocated how would I put the token strings into the array?

Any help is appreciated thank you

🌐
YouTube
youtube.com › portfolio courses
Dynamically Allocate Memory For An Array Of Strings | C Programming Example - YouTube
How to dynamically allocate memory for an array of strings using C. Source code: https://github.com/portfoliocourses/c-example-code/blob/main/dynamic_array_...
Published   January 21, 2022
Views   49K
🌐
Diveintosystems
diveintosystems.org › book › C2-C_depth › strings.html
2.6.1. C's Support for Statically Allocated Strings (Arrays ...
In the previous chapter we introduced arrays and strings in C. In this chapter we discuss dynamically allocated C strings and their use with the C string library.