Value from the pointer is not displaying correctly

0

I try to assign some information to 'char' data (one structure and one integer value), but after i assign it i can't read it back. Any solution? I work on Ubuntu 16.04 installed on virtualbox

struct opcode_struct{
    uint8_t a;
    uint8_t b;
    uint8_t c;
    uint8_t d;
};

union opcode{
    uint32_t uint32code;
    struct opcode_struct code;
};

struct request{
    //4
    union opcode opc;
    //4
    uint32_t id;
};


int main()
{
    char *buff = (char*)malloc(32);

    struct request rq = {0x00000001, 0}, *ptr_rq = &rq;
    int val = 512, *ptr_int = &val;

    memcpy(buff, ptr_rq, sizeof(rq));
    memcpy((buff+sizeof(rq)), ptr_int, sizeof(int));

    printf("Request opcode: 0x%08x\n", *buff);
    printf("Request id: %d\n", *(buff+sizeof(uint32_t)));
    printf("Int value: %d\n", *(buff+sizeof(rq)));

    free(buff);
    return 0;
}

Displayed text: Request opcode: 0x00000001 Request id: 0 Int value: 0

but Int value should be equal to '512'

c
ubuntu-16.04
asked on Stack Overflow Jun 18, 2019 by StrollingOx

1 Answer

0

You're dereferencing buff+sizeof(rq), which is a char *. Since 512 is 0x 02 00, if you dereference it as a char * you get 0x00. If you look in buff+sizeof(rq) + 1, you get the other 0x02.

On the other hand, if you cast the pointer to int *, then you get the full 0x0200.

printf("Int value: %d\n", *(int *)(buff+sizeof(rq)));

outputs 512.

answered on Stack Overflow Jun 18, 2019 by ODYN-Kon • edited Jun 18, 2019 by ODYN-Kon

User contributions licensed under CC BY-SA 3.0