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?
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.