【问题标题】:weird output of spliting char array in C在 C 中拆分 char 数组的奇怪输出
【发布时间】:2021-09-08 23:38:29
【问题描述】:

我在 Linux 中的服务器端 Socket(使用 Telnet 客户端)上工作。客户端需要以特定格式输入一行:(1)命令(GET/PUT/DEL),(2)键和(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;
            }

【问题讨论】:

标签: c sockets ipc


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多