C - 使用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(( 函数。

最新更新