在 C 中拆分字符数组的奇怪输出

用户12595983

我在 Linux 的服务器端套接字(使用 Telnet 客户端)上工作。客户端需要以某种格式输入一行:(1)command(GET/PUT/DEL)、(2)key 和(3)关联值(中间有空格)。这个键值对随后相应地传递给函数(GET/PUT/DEL),该函数将数据保存在共享内存(keyValueStore)中。

我尝试将输入分成 3 部分,但在读取 Token(2) 时出现了奇怪的结果。

  • 我可以知道原因吗?关于如何更改我的代码的任何建议?(我期望的是 key1, key2 )

谢谢!

在此处输入图片说明

int main() {

...
    char input[BUFSIZE]; // Client Daten -> Server
    int bytes_read; // Bytes von Client

...

        while (1) {

            int bytes_index = -1;
            while (1) {

                bytes_read = recv(cfd, &input[++bytes_index], 1, 0);
                if (bytes_read <= 0)  // Check error or no data read
                    break;

                if (input[bytes_index] == '\n') {
                    // Received a complete line, including CRLF
                    // Remove ending CR
                    bytes_index--;
                    if ((bytes_index >= 0) && (input[bytes_index] == '\r'))
                        input[bytes_index] = 0;
                    break;
                }
            }
            if (bytes_index > 0) {   // Check for empty line
                printf("%s\n", input);
                printf("bytes_index: %d\n", bytes_index);

                //get the first token
                token = NULL;
                token = strtok(input, " ");
                //walk through other tokens
                int i = 0;
                while (token != NULL) {
                    strcpy(&input[i++], token);
                    printf("Token: %d : %s\n",i, token);
                    token = strtok(NULL, " ");
                }
                // Check for client command

                if (strcmp(input, "QUIT") == 0)
                    break;
            }
麦克猫

的结果strtok()引用源缓冲区,因此通过在重叠对象之间执行复制来strcpy(&input[i++], token);调用未定义的行为

在这种情况下,您应该简单地删除该行,因为复制的结果看起来没有被使用。

如果您想在将来使用令牌,您应该以不同的方式存储它们。存储指向每个令牌的指针可能会起作用(直到将新数据读取到input)。它会是这样的:

char* tokens[BUFSIZE];
while (token != NULL) {
    tokens[i++] = token;
    printf("Token: %d : %s\n",i, token);
    token = strtok(NULL, " ");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章