Search code examples
carraystype-safety

Is memcpy of array in C Vaxocentrist?


Is a memcpy of a chunk of one array to another in C guilty of Vaxocentrism?

Example:

double A[10];
double B[10];
// ... do stuff ...
// copy elements 3 to 7 in A to elements 2 to 6 in B
memcpy(B+2, A+3, 5*sizeof(double)

As a related question, is casting from an array to a pointer Vaxocentrist?

char A[10];
char* B = (char*)A;
B[0]=2;
A[1]=3;
B[2]=5;

I certainly appreciate the idea of writing code that works under different machine architectures and different compilers, but if I applied type safety to the extreme it would cripple many of C's useful features! How much / little can I assume about how the compiler implements arrays/pointers/etc.?


Solution

  • No. The model on which memcpy works is defined in the abstract machine specified by the C language standard and has nothing to do with any particular physical machine it might be running on. In particular, all objects in C have a representation which is defined as an overlaid array of type unsigned char[sizeof object], and memcpy works on this representation.

    Likewise, the 'decay' of arrays to pointers via cast or implicit conversion is completely defined on the abstract machine and has nothing to do with physical machines.

    Further, none of the points 1-14 in the linked article have anything to do with the code you're asking about.