Thread: memcpy, malloc and a world of pain!

1. memcpy, malloc and a world of pain!

Hi

I am trying to combine two uint8_t values into a single uint16_t value, however no matter what I try I keep getting segmentation faults. Can someone explain to me what I am doing wrong – it would be greatly appreciated!

Thanks

Code:
int combineHex(uint8_t x, uint8_t y) {

uint16_t *temp = malloc(16);
int value;

if(temp != NULL) {
memcpy(&temp, &x, 8 );
memcpy(&temp+8, &y,8);
// do something with temp
} // if

free(temp);

return value;

} // combine

2. temp+8 moves, not 8 bytes, but 8 of <whatever temp is>, so you're looking at 8x16 bytes down the road.

3. Oh right – If that’s the case how would I go about getting two 8 bit numbers into a single 16 bit number?

03 & FF = 03FF

Many thanks

4. Why not result = 03 * 0x100 + FF?

5. My friend you are an utter genius! Thank you very much – That has been bugging me for hours!

6. why not to
Code:
uint16_t res = x;
res <<= 8;
res |= y;

7. Code:
int combineHex(uint8_t x, uint8_t y) {

uint16_t *temp = malloc(16);
int value;

if(temp != NULL) {
memcpy(&temp, &x, 8 );
memcpy(&temp+8, &y,8);
// do something with temp
} // if

free(temp);

return value;

} // combine
If you want to do things like this, it's best to work with uint8_t (unsigned char) because it's only one byte.
Plus you're passing the address of the pointer to malloc which expects a pointer to allocated memory. Since temp is only 4 bytes, you're getting a nasty buffer overrun.

http://cpwiki.sf.net/Buffer_overrun

That mentioned, vart's idea is the simplest and the least error prone way of doing it, so go with that instead.