Returning a pointer to dynamically allocated memory from a function

I need to dynamically allocate memory in a function and then return a pointer to it. Could someone verify if this is the correct way to do this and that it doesn't have any problems like leaking memory?

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
30
31
32
33
34
#include <iostream>

using namespace std;

char *duplicate(const char *);

int main() {
	char a[] = "Hello";
	char *a2;

	cout << "a: " << a << endl;
	a2 = duplicate(a);
	cout << "a2: " << a2 << endl;
	delete[] a2;

	return 0;
}

char *duplicate(const char *source) {
	int count = 0;
	while (source[count] != '\0') {
		count++;
	}
	
	char *cpy = new char[count + 1];
	count = 0;

	while (source[count] != '\0') {
		cpy[count] = source[count];
		count++;
	}
	cpy[count] = '\0';
	return cpy;
}
Nicely done.
Thanks!
You have done well.
But normally I wouldn't do this. I'll pass a writable buffer to duplicate() method, and take care of the memory outside the duplicate() method.
"duplicate" is a common non-standard function called strdup().
https://linux.die.net/man/3/strdup

It is C-style all the way.
Topic archived. No new replies allowed.