繁体   English   中英

C-传递给另一个函数后,缓冲区大小减小

[英]C - Buffer size reduced after being passed to another function

我正在使用C进行赋值,并且在跟踪错误时遇到了一些我作为初学者不了解的东西。

我正在做的是将一些变量存入函数l1_connect()的缓冲区:

int l1_connect(const char* hostname, int port) {
    // Variables to be stored in the buffer
    char *msg = "Hi, I'm a message"; // strlen(msg) == 17
    uint16_t sender_id = htons(1); // sizeof(sender_id) == 2
    uint16_t packet_size = htons(sizeof(packet_size)+sizeof(sender_id)+strlen(msg)); // sizeof(packet_size) == 2

    // The buffer
    char buf[100];

    // Copying everything
    memcpy(&buf, &sender_id, sizeof(sender_id));
    memcpy(&buf+sizeof(sender_id), &packet_size, sizeof(packet_size));
    memcpy(&buf+sizeof(sender_id)+sizeof(packet_size), &msg, strlen(msg));

    printf("l1_connect - sizeof(buf): %d\n", (int)sizeof(buf)); // == 21

    // Passing buf to another function
    int bytes_sent = l1_send(1, buf, sizeof(buf));

    return bytes_sent;
}

在此函数的最后,缓冲区的大小为21。但是,将其传递给另一个函数后,显然是8。

int l1_send( int device, const char* buf, int length ) {
    printf("l1_send - Sizeof buf: %d\n", (int)sizeof(buf)); // == 8
    printf("l1_send - Sizeof &buf: %d\n", (int)sizeof(&buf)); // == 8
    printf("l1_send - Sizeof *buf: %d\n", (int)sizeof(*buf)); // == 1
    printf("l1_send - Sizeof &buf[0]: %d\n", (int)sizeof(&buf[0])); // == 8

    return 1; // For now
}

谁能向我解释我所缺少的吗?

我正在尝试通过UDP套接字发送缓冲区,然后再次提取这三个变量。 提取sender_idpacket_size效果很好,但是消息不断给出错误或空值,我认为这是因为缓冲区大小问题。

谢谢!

编辑:非常感谢,伙计们! 我开始意识到为什么我们将length传递给l1_send()

sizeof是一个运算符,它返回变量类型的大小,而不是分配的缓冲区的大小。

因此,在似乎是64位计算机上:

// l1_send

sizeof(buf) --> size of char * --> 8 bytes
sizeof(&buf) --> size of char ** --> 8 bytes
sizeof(*buf) --> size of char --> 1 byte
sizeof(&buf[0]) --> size of char * --> 8 bytes

// l1_connect
sizeof(buf) --> size of char[100] --> 100 bytes (that's what it should be)

要获取数组的大小,应使用以下代码段:

int buff[100];
int buff_size = sizeof(buff) / sizeof(buff[0]);

除此之外,根据架构的不同,指针sizeof一定会获得48个字节。 因此,当您从数组转换为指针时,会发生某种信息丢失

// The buffer
char buf[100];
const char * buff_size = buf; 

sizeof(buf);  // This is valid
sizeof(buff_size); 

后来的编译器也不知道它指向的位置。 由于sizeof()在编译时有效,因此sizeof(buff_size)将返回8个字节

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM