The above code compiles and runs, leading me to believe that memory
reallocation is taking place.
Just because the program appears to behave as you expect does not mean that it is correct, or even that its behavior is defined at all from C's perspective.
However when applied on a greater scale
(recursively also), I receive memory errors in random places
(different each time the program is run).
Could strcat_s()
be exceeding boundaries?
Yes.
Is realloc()
therefore
required to ensure the memory is properly allocated?
No.
Neither strcat_s()
nor strcat()
performs any reallocation. They are not specified to do so, and it would be unsafe for them to do so.
You receive errors because you are using the function incorrectly (even when you don't get errors). It is your responsibility to ensure that the second argument does not exceed the size of the array pointed to by the first, but you are flagrantly disregarding that responsibility. I presume you simply have a serious misunderstanding about what strcat_s()
is supposed to do, and what its second parameter means.
The main thing that strcat_s()
provides but strcat()
doesn't is checking that the specified array bounds are not overrun as a result of the second string being longer than can be accommodated. This relieves you of checking the length of the second string before performing the concatentation, which is advantageous because strcat_s()
can do that itself at very low cost, since it must scan that string anyway. strcat_s()
has no more ability than any other C operation or function to determine independently how long is the array to which the first argument points. It relies on you to tell it.
If you need to accommodate dynamic adjustment of your array size, then that's your responsibility, as is tracking the current size of the allocation.