replacestr is my function. It does assume that you have enough buffer to store the result.

All kinds of similar algoritms that has a variable output length can assume to increase performance but will be unsafe to use; if you're making a text editor that has to handle all kinds of input and output ranges that can be fatal.

A solution would be to count the amount of linefeeds before the allocating the buffer, another would be to let replacestr to handle resizable strings; which isn't in good because in general you want to be able to operate on the stack as well. And if you reallocate often, even once in the latter part the copying process will be slower than a search algoritm itself.

To automate the process of counting occurances of search criteria and multiply it with length of rep-length of crt, and as well save performance by generating an array of pointers to the found substrings in the source string, I could split up the algoritm in two functions, one that will be search, and the other replace. Search will fill an array with found results and return the number of total founds for the sake if the array gets filled. Replace will then process a target string with the replacements using the found elements array. Then you could safely allocate the buffer and pass it as target.