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

时间:2015-04-27 21:18:50

标签: c sockets

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

    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);

3 个答案:

答案 0 :(得分:3)

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);

答案 1 :(得分:2)

您阅读的数据不会以'\0'字符终止,因此您无法将其视为字符串。

答案 2 :(得分:1)

您的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 );