I used memcpy to copy the contents of one pointer to another pointer assigned to new memory. Later in the program I get runtime errors as if I were attempting to operate on a pointer pointing to nothing. While debugging, I saw that the original and the the copied pointer had different addresses but they acted as if they were one, for example If I set a property of the copied pointer to 'a' the original would also get set to 'a'. In this case I delete the copied pointer and the original gets deleted too as if they pointed to the same memory.

I dont use memcpy often, as far I understand it copies memory of one object to another basically creating a clone
This is how i used it:

    T* toreturn = new T;
    memcpy(toreturn, pr, sizeof(*pr));
4 Years
Discussion Span
Last Post by James19142

The correct way to do this would be to create a "copy constructor" for your class T.

The way you are doing it will only work if none of the members of T are pointers and do not contain objects which contain pointers.

If T is very simple, with simple numbers or fixed sized arrays it should work but is inelegant.

If any members of T do new or malloc or something like that you may well be better off with a copy constuctor. Then you source code would read like this:

T* roreturn = new T (*pr)

all the classes T would stand for did have a lot of pointers which would explain the odd behavior. It makes sense that they wouldn't be correctly assigned in a blind copy, but still probably pointing to the same addresess.

Edited by James19142


I dont use memcpy often

As well you shouldn't. memcpy() is a very low level function that was inherited from C. The problem with memcpy() in C++ is that it doesn't respect class structure or construction/destruction, so unless you have what is called a POD type, use of memcpy() is undefined. My usual recommendation is to forget memcpy() exists unless your code is C compatible.

The usual shallow copying problems present in C were also inherited, such that if you copy a pointer, only the address gets copied and not whatever the pointer points to. That results in an alias that, when unintended, wreaks havoc on memory.


I took memcpy out and replaced it with a manual copy constructor and everything works perfect. Now that I think about it, I could've used it then corrected the pointers afterwards, but for the most part I guess I'll avoid memcpy and use it for storage-like classes only.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.