overflow when using uint32_t

2.1k views Asked by At
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

char* createMSG(uint8_t i,uint32_t port);

int strlen(char* tmp);
uint32_t user_port = 5000;

int main(int argc, char** argv) {
    char *msg;
    uint8_t i;
    i = 1;  
    msg = createMSG(i,user_port);
    printf("Port: %d",*(msg+2));
}

char* createMSG(uint8_t i,uint32_t port) {
    char *buff; 
    buff = (char*) malloc(6);
    uint8_t id;
    id = 2;
    memcpy(buff, &id, sizeof(uint8_t));
    memcpy(buff+1, &i, sizeof(uint8_t));
    memcpy(buff+2, &port, sizeof(uint32_t));
    return buff;
}

The output is: "Port: -120". It seems there is some overflow. But uint32_t should be big enough for 5000. When using 22 instead of 5000, everything is ok.

Why?

2

There are 2 answers

6
Viktor Latypov On BEST ANSWER

This line

printf("Port: %d",*(msg+2));

prints the 'char' value at (msg+2) address, not the uint32_t !

Use

uint32_t PortFromProc = *(uint32_t*)(msg+2);
printf("Port: %d", PortFromProc);

To "fix" port numbers from recvfrom() function one must use the ntohl() function.

1
K-ballo On

Because *(msg+2) has type char. If you really want to do that, you should do

printf("Port: %d",*(uint32_t*)(msg+2));

As noted by @R.., msg+2 almost certainly does not meet the right alignment requirements for type uint32_t. If the code appears to work, it's an accident and not portable.