Search code examples
coverflowuint32-t

overflow when using uint32_t


#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?


Solution

  • 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.