You have quite a few off-by-1 errors, as well as some other flawed logic.
- line 6 increments 'src' (changing what it points to), so that when you copy the string on line 12, 'src' no longer points to the start of the string.
- line 9 allocates 'length+1' char for dest, which is good. But notice that if you're copying length+1 chars, your copy loop on line 12 is
already copying the null terminator. So there's not need to explicitly place it again on line 15
- line 15 would be wrong anyway, as you're indexing by [++j]... which basically is j+1, and since j==i at that point, j+1 would be one char
after the null terminator. Since j+1 >= i, that line is corrupting the heap.
- passing 'dest' as a parameter to strcpy2 does not do anything because you're passing the pointer by value. The 'dest' in strcpy2 and the 'dest' in main are two different variables. Therefore the 'dest' in main is always null because you never assign it, and whatever pointer you pass as 'dest' to strcpy2 goes unused, since you reassign it right away. This also has the side-effect of producing a memory leak becaues you're delete[]ing main's dest (which is not doing anything because that dest is a null pointer), and you are never delete[]ing strcpy2's 'dest'.
You probably meant to pass 'dest' by reference. Something like this would behave more as you seem to expect:
|
char* strcpy2(char*& dest, const char* src){ // note the *&. Passing the pointer by reference
|