There are minor improvements that can be made to the code, mostly just cosmetic, stylistic, and the like, even for readability that is bad.
You could put a null character at the end to become a string and it would not need the loop to print the string . Whichever is wrong, the only solution to resolve the size to be printed is the null character or also to return the size somehow. In fact, 5 is wrong.
Note that you are unlikely to want to leave unlimited entry. And there is usually nothing wrong with allocating the maximum value that the string can be input. Even if the maximum is a little too large, you can still optimize the allocations.
It is common to start with a minimum size, type 16, 64, 256 or even more. And double up the allocation with realloc()
whenever you pop the capacity. You have to control the occupied size and confront with the total capacity to decide to relocate.
In addition, sizeof(char)
is always 1, so this is unnecessary, cast (char*)
is unsuitable in C.
You do not need to make the first allocation as an exception in if
, realloc()
is enough from the start pointer to null.