memcpy(), what should the value of the size parameter be?
As long as dst
is declared as an array with a size, sizeof
will return the size of that array in bytes:
int dst[ARRAY_LENGTH];
memcpy( dst, src, sizeof(dst) ); // Good, sizeof(dst) returns sizeof(int) * ARRAY_LENGTH
If dst
just happens to be a pointer to the first element of such an array (which is the same type as the array itself), it wont work:
int buffer[ARRAY_LENGTH];
int* dst = &buffer[0];
memcpy( dst, src, sizeof(dst) ); // Bad, sizeof(dst) returns sizeof(int*)
If you have allocated using malloc you must state the size of the array
int * src = malloc(ARRAY_LENGTH*sizeof(*src));
int * dst1 = malloc(ARRAY_LENGTH*sizeof(*dst1));
memcpy(dst1,src,ARRAY_LENGTH*sizeof(*dst1));
If you have allocated with a static array you can just use sizeof
int dst2[ARRAY_LENGTH];
memcpy(dst2,src,sizeof(dst2));
sizeof(dst)
is correct only if dst
is an array which size is known at compile time: like int arr[ARRAY_LENGTH]
or a C99 variable length array; otherwise it returns the size of a pointer, not the length of the destination array.
To avoid future bug, be consistent and prefer the first form: size of type * length.