M
Martin
For reasons I won't go into, I need to transfer from 1 to 3 bytes to a
variable that I know is 4 bytes long. Bytes not written to in the 4-byte
target variable must be zero. Is the following use of memcpy() a
well-defined way of so doing? The code is written knowing that
sizeof(unsigned long) == 4 in this instance. The code is somewhat contrived
in order to provide a self-contained program that will compile and show the
use of memcpy() I am asking about.
The following code clean compiles using
gcc -Wall -ansi -pedantic
where
gcc -dumpversion displays
4.10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
unsigned long value;
unsigned char *pAddress;
unsigned char rem;
pAddress = malloc(3);
if ( pAddress == NULL )
{
puts("malloc failed");
exit(EXIT_FAILURE);
}
/* load in some arbitrary values */
pAddress[0] = 1;
pAddress[1] = 2;
pAddress[2] = 4;
rem = 3; /* hard-wired for demo - normally calculated */
if ( rem )
{
value = 0;
memcpy( &value, pAddress, rem );
}
/* for demo - shows values in pAddress have been transferred */
printf("value = 0x%0lX\n", value);
return 0;
}
variable that I know is 4 bytes long. Bytes not written to in the 4-byte
target variable must be zero. Is the following use of memcpy() a
well-defined way of so doing? The code is written knowing that
sizeof(unsigned long) == 4 in this instance. The code is somewhat contrived
in order to provide a self-contained program that will compile and show the
use of memcpy() I am asking about.
The following code clean compiles using
gcc -Wall -ansi -pedantic
where
gcc -dumpversion displays
4.10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
unsigned long value;
unsigned char *pAddress;
unsigned char rem;
pAddress = malloc(3);
if ( pAddress == NULL )
{
puts("malloc failed");
exit(EXIT_FAILURE);
}
/* load in some arbitrary values */
pAddress[0] = 1;
pAddress[1] = 2;
pAddress[2] = 4;
rem = 3; /* hard-wired for demo - normally calculated */
if ( rem )
{
value = 0;
memcpy( &value, pAddress, rem );
}
/* for demo - shows values in pAddress have been transferred */
printf("value = 0x%0lX\n", value);
return 0;
}