[quote author=L0aD1nG link=topic=18444.msg99273#msg99273 date=1422529570
Now this is the only thing I kinda disagree cause if its about specifying the size each time, it won't be "infinite" right? Plus that the reallocations won't be that many, cause I double the size its time. But yea sure if its about file scanning it would help to start from a bigger size, though I still didn't use it for file scanning.
After all, I will customize-update the function.
Thank you so much for all that important notes mate!
[/quote]
Huh? :S... I'm talking about a default allocation size. Why would that make it non-"infinite" by parameterizing a default allocation size to start with before any reallocation calls?
You can't say that the reallocations won't be many because you don't know what the size of the input will be. Reallocation is expensive too, so if you need a large buffer, and you allocate 16 by default, then you're going to require multiple reallocations in order to reach a sufficient buffer size, but in other parts of your code perhaps you only need a couple bytes. Even to satisfy both cases in the best way and cut the default allocation to a point in the middle of the smallest allocation size you need and the largest, doesn't make any sense, because now you oversize a buffer, and still require reallocation for the larger buffer. I don't see any issue with parameterizing this to solve this problem IMHO. Additionally, heap allocation is slower than stack allocation.
Ideally allocation should be a one time thing. Anything that requires reallocation makes it easier to use in this case, but very inefficient. It would be better to determine the allocation size required before populating an allocated buffer and determining when it needs to be reallocated into a larger storage space.
My comment about malloc() too, in this case does not serve any purpose, but helps avoid issues when malloc() is not properly prototyped (by inclidng <stdlib.h>). The implicit casts are defined by the standard, there's really no benefit to being explicit about them (literally not a single benefit). It can actually be very bad casting the return of functions like malloc() that return void.
edit: That reallocation to fit the buffer size is really not necessary either, and it's actually not proper since you are setting it to the size of the 0-based index, and not the number of elements (including the null terminator). You essentially realloc() to cut the null terminator off... That is wrong. The final reallocation should be a buffer with size index + 1, not index.
Here is a good error checking function:
http://stackoverflow.com/questions/4023895/how-to-read-string-entered-by-user-in-c/4023921#4023921