0
char* createMSG(uint8_t i,uint16_t port) {
char *buff; 
buff = (char*) calloc(1,6);
uint8_t id, tmp;
tmp = 0;
id = 2;
memcpy(buff, &id, sizeof(uint8_t));
memcpy(buff+1, &i, sizeof(uint8_t));
memcpy(buff+2, &port, sizeof(uint16_t));
memcpy(buff+2+2, &tmp, sizeof(uint16_t));
memcpy(buff+2+2+1, &tmp, sizeof(uint16_t));
printf("created SV_CON_REP: id: %d accept: %d port %d\n",*buff,*(buff+1),*    (buff+2));    return buff;
}

I need to copy the port in an uint32_t. It prints that port is Null.

EDIT Function call: char* tmp; uint8_t i; i = 9; uint16_t port; port = 1234; tmp = createMSG(i,port);

Output: created MSG: id: 2 accept: 0 port 0

user1324258
  • 561
  • 2
  • 8
  • 25

2 Answers2

0

How about *((uint_16*)(buff+2)) in printf?

malenkiy_scot
  • 16,415
  • 6
  • 64
  • 87
0

I was copy this function, but under windows.

uint8_t = BYTE
uint16_t = WORD

char* createMSG(BYTE i,WORD port) 
{
    char *buff; 
    BYTE id, tmp;
    buff = (char*) calloc(1,6);
    tmp = 0;
    id = 2;
    memcpy(buff, &id, sizeof(BYTE));
    memcpy(buff+1, &i, sizeof(BYTE));
    memcpy(buff+2, &port, sizeof(WORD));
    memcpy(buff+2+2, &tmp, sizeof(WORD));
    memcpy(buff+2+2+1, &tmp, sizeof(WORD));
    printf("created SV_CON_REP: id: %d accept: %d port %d\n",*buff,*(buff+1),*        (buff+2));    return buff;
}

call:

createMSG(9,1234);  

printf result:

created SV_CON_REP: id: 2 accept: 9 port 210

(1234 = 0x04d2, where 0xd2=210)

you still not copy call & printf result, but your own comment

BenMorel
  • 34,448
  • 50
  • 182
  • 322
theWalker
  • 2,022
  • 2
  • 18
  • 27
  • by the way, change any char to unsigned char. this may be very strange error (but not in this case) – theWalker May 21 '12 at 22:27
  • whats after REM this line?: memcpy(buff+2+2+1, &tmp, sizeof(uint16_t)); – theWalker May 21 '12 at 22:32
  • I made a mistake. The last memcpy is not necessary. It can even cause a error because we have allocated only 6 bytes. So we havte to remove this line memcpy(buff+2+2+1, &tmp, sizeof(uint16_t)); – user1324258 May 21 '12 at 22:45
  • I know, this override the buffer 6B by 1B, but check it. try to check any ideas by run the code. Check please, whats after memcpy(buff, &port, sizeof(WORD)); and then printf("created SV_CON_REP: 1: %d 2: %d 3 %d 4 %d 5 %d 6 %d\n",*buff,*(buff+1),*(buff+2),*(buff+3),*(buff+4),*(buff+5),*(buff+6)); without others memcpy. – theWalker May 21 '12 at 23:02
  • the next "small" error is: uint8_t tmp; an then: memcpy(buff+2+2, &tmp, sizeof(uint16_t)); This is after copy i & tmp, but please delete this line an next one; calloc() initalizes memory by zeroes. – theWalker May 21 '12 at 23:11