char[] 在 strcpy 之后具有重复值

char[] with duplicate value after strcpy

我有一个包含两个字符数组变量(id 和 id_partner_expected)的结构,当我在第二个数组上使用 strcpy 时,第一个数组也发生了变化。我尝试了我所知道的一切,但没有预期的结果:(

#define SIZE_CLIENT_ID 15

struct client_infos {
    char addr[INET_ADDRSTRLEN];
    int socket;
    char id[SIZE_CLIENT_ID];
    char id_partner_expected[SIZE_CLIENT_ID];
    struct client_infos* partner;
};

char buffer_received[MAX_CLIENT_IO];


while ((len_received = recv(c->socket, buffer_received, MAX_CLIENT_IO, 0)) > 0) {

    if (strlen(c->id) == 0) {
        //First step: Identify the client

        strcpy(c->id, buffer_received); // FIRST LOOP

    } else if (strlen(c->id_partner_expected) == 0) {
        //Second step: Identify/Connect the partner


        strcpy(c->id_partner_expected, buffer_received); // SECOND LOOP

    }

    printf("Received %d bytes from client %s, with id %s", len_received, c->addr, c->id);
    printf("%d\n", strlen(c->id));//STRCPY DUPLICATING CONTENT OF C->ID ???!!!
}

结果:

1º 循环:

从客户端 0.0.0.0 收到 15 个字节,id 为 0000654987321 15

2º循环:

从客户端 0.0.0.0 收到 15 个字节,id 为 0000654987321 6544sssss5555 30

但预期的结果是:

2º循环:

从客户端 0.0.0.0 收到 15 个字节,id 为 0000654987321 15

原始来源在这里: https://github.com/fernandobatels/blitz-p2p-bridge/blob/master/src/api.h https://github.com/fernandobatels/blitz-p2p-bridge/blob/master/src/api.c

感谢大家的帮助:)

C 字符串以零结尾。您从网络收到的字符串显然不是。收到数据后需要zero-terminate字符串:

...
while ((len_received = recv(c->socket, buffer_received, MAX_CLIENT_IO, 0)) > 0) {
    buffer_received[len_received] = 0; // add this line
    if (strlen(c->id) == 0) {
    ...

另请注意,由于您的最大 ID 长度(以及从网络接收的最大数据量)为 15,因此您需要将数组扩展一个字符以为终止零腾出空间:

struct client_infos {
    char addr[INET_ADDRSTRLEN];
    int socket;
    char id[SIZE_CLIENT_ID + 1];
    char id_partner_expected[SIZE_CLIENT_ID + 1];
    struct client_infos* partner;
}

char buffer_received[MAX_CLIENT_ID + 1];