Me myself and I
Me myself and I

Reputation: 4070

Runtime error when copying bytes from array

I'm trying to make a copy of an array. I know this is "bad code" but I'm getting it from a tutorial that makes heavy use of this and other low-level things. For some reason I'm getting a runtime error and I can't tell where it's coming from or why. Can anyone help? Thanks.

#include <iostream>

void copy_array(void *a, void const *b, std::size_t size, int amount)
{
    std::size_t bytes = size * amount;
    for (int i = 0; i < bytes; ++i)
        reinterpret_cast<char *>(a)[i] = static_cast<char const *>(b)[i];
}

int main()
{
    int a[10], b[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    copy_array(a, b, sizeof(b), 10);

    for (int i = 0; i < 10; ++i)
        std::cout << a[i] << ' ';
}

Upvotes: 1

Views: 96

Answers (1)

Captain Obvlious
Captain Obvlious

Reputation: 20073

The expression sizeof(b) returns the size of the array in bytes not the number of elements in the array. This causes the copy function to overwrite the stack frame resulting in a runtime error. Use sizeof(b[0]) instead to get the size of an individual element. If you want to retrieve the number of elements in an array you can use a combination of the two like so.

copy_array(a, b, sizeof(b[0]), sizeof(b) / sizeof(b[0]));

Upvotes: 1

Related Questions