With a run time error of "Stack around the variable 'temp' was corrupted" usually means that you tried to access an array outside the size or boundary of an array.
If I were in the bunch of the good C++ programmers, I would try to give you an answer; since I'm not, I can only point out that your code does not compile and you did not provide input data to test. That makes your question more suitable for clairvoyants than programmers.
However, these instructions of yours are really dangerous:
Are you sure to know what’s in that memory area?
For what I can see in your code, "destpos" could be incremented only by one 'step', but you could try to access the memory two 'steps' lower.