#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 时,一切正常。
为什么?