繁体   English   中英

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

[英]Reading from socket in C giving weird output

我无法从套接字读取信息。 我正在使用的代码如下,有时它可以很好地工作,但在其他时候,它只打印一些不可读的字符,或一些随机可读的字符……有更好的方法吗?

    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中的字符串必须以空字符结尾,这意味着它们的最后一个字符必须带有符号\\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);

您读取的数据不会以'\\0'字符结尾,因此您不能将其视为字符串。

您的char数组不能保证以null结尾。 这意味着printf可能会打印出比数组中更多的内容,因为它会寻找一个空终止以停止输出字符。

您也不要在使用之前初始化分配的内存,这是一种不好的做法,因为内存可能包含随机垃圾。

为了使代码更好地工作并希望解决您的问题,您应该执行以下操作:

char* answer = malloc(1024 + 1); /* add extra byte for null terminator */
/* other variables the same */

memset( answer, '\0', 1024 + 1 ); /* initialise memory before use */
while (answerLength < 1024 && read(sock, &newChar, 1) > 0 ) {
    /* loop is the same */
}
printf("%s\n", answer);

printf还有一个参数,它将告诉它打印一定数量的字符。 像这样:

printf( "%.*s\n", answerLength, answer );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM