char* copy function

Can someone tell me why this generates garbage output for 'Destination'? It's supposed to copy one char* to another char*, similar to strcpy. Looking at the debugger, it looks like the problem is on line 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>

char* strcpy2(char* dest, const char* src) {
	int i = 1;
	while (*src++) {
		++i;
	}
	dest = new char[i];
	int j = 0;
	while (j < i) {
		dest[j] = src[j];
		++j;
	}
	dest[++j] = 0;
	return dest;
}

int main() {
	std::string word;
	std::cout << "Input a string: ";
	std::cin >> word;

	const char* src = word.c_str();
	char* dest = 0;
	std::cout << "Source: " << src << ", Destination: " << *strcpy2(dest, src) << std::endl;
	delete [] dest;
	system("pause");
}
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 
Last edited on
Topic archived. No new replies allowed.