gpt4 book ai didi

c - 从 C 中的套接字读取给出奇怪的输出

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:58 25 4
gpt4 key购买 nike

我在从套接字读取时遇到问题。我正在使用的代码如下,有时它工作得很好,但有时它只是打印一些不可读的字符,或者一些随机可读的字符......有更好的方法吗?

    char* answer = (char*) malloc(1024);
int answerLength = 0;
char prevChar = 0;
char newChar = 0;
while (answerLength < 1024 && read(sock, &newChar, 1) > 0 ) {

if (newChar == '\n' && prevChar == '\r') {
break;
}
printf("%d\n", answerLength);
answer[ answerLength ] = newChar;
answerLength++;

prevChar = newChar;
}
printf("%s\n", answer);

最佳答案

C 中的字符串必须以 null 结尾,这意味着它们必须有一个符号 \0 作为最后一个字符。

由于您不能保证它会在您的代码中的任何地方发生,answer 可能会在您读取的数据旁边填充内存垃圾。

要确保它不会发生,请使用:

answer[answerLength] = '\0';
printf("%s\n", answer);

此外,您可以直接read() 整个内容到answer,您不需要那个毫无意义的循环:

int len;
while (len = read(sock, &answer[answerLength], 1024 - answerLength))
answerLength += len;
answer[answerLength] = '\0';
printf("%s\n", answer);

关于c - 从 C 中的套接字读取给出奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com