【发布时间】: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;
}
【问题讨论】:
-
strtok()的结果指向源缓冲区,因此strcpy(&input[i++], token);通过在重叠对象之间执行复制来调用未定义行为。