Search code examples
c++memorymemcpy

Why is memcpy not copying the data I give to it?


I'm making a memory manager/allocator in C++. The function "memcpy" doesn't seem to be working as expected. Here's the offending code:

template <class Type>
Data<Type> MemoryManager::alloc(Type* data) {
    ...
    printf("Allocating data of size %i at local address %i, absolute address %i\n", allocSize, allocAddress, allocStart + allocAddress);
    ...
    std::cout << *data << std::endl;
    memcpy(data, (Type*)(allocStart + allocAddress), allocSize);
    std::cout << *(Type*)(allocStart + allocAddress) << std::endl;
    ...
}

For a test, I tried allocating an integer with a value of 20. What gets outputted to standard output when I run this test is this:

Allocating data of size 4 at local address 0, absolute address 16834208
20
-842150451

As you can see, data (which is a pointer to a Type) is pointing to the correct value of 20 when I attempt to dereference. However, after using memcpy to copy to the new address (also a pointer to a Type), the value has become -842150451. What's interesting is that it's always this number, no matter what I test with, no matter what the actual address ends up being. Also, this number is not the minimum value for an integer on my system - as you can see, the size of an integer is 4 bytes. So what is this number? And why does memcpy always copy it into my address instead of the data I've given it?

EDIT: I had the arguments in the wrong order. Problem solved. But my second question remains, what is that number, and why is it always copied in no matter what my source is?


Solution

  • The First Argument should be Destination and second should be source Like This :

    void * memcpy ( void * destination, const void * source, size_t num );
    

    A simple example :

    char myname[] = "Pierre de Fermat";
    /* using memcpy to copy string: */
    memcpy ( person.name, myname, sizeof(myname) );