簡體   English   中英

使用uint32_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;
}

輸出為:“端口:-120”。 似乎有一些溢出。 但是uint32_t應該足以容納5000。使用22而不是5000時,一切正常。

為什么?

因為*(msg+2)具有char類型。 如果您確實想這樣做,則應該這樣做

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

@R ..所指出的,msg + 2幾乎可以肯定不滿足uint32_t類型的正確對齊要求。 如果該代碼似乎可以正常工作,那是偶然的情況,不是可移植的。

這條線

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

在(msg + 2)地址上打印'char'值,而不是uint32_t!

采用

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

要從recvfrom()函數“修復”端口號,必須使用ntohl()函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM