具有永不返回的C字符串的函数

时间:2013-08-28 15:44:03

标签: c string malloc strtok

我是新来的。我有一个问题,我完全不知道是什么原因造成的! 我希望有人可以帮助我。 我正在开发一个带有socket的小型TCP服务器,它接收来自客户端的字符串并且必须在其上做一些事情。 程序在此函数中保持阻塞状态,永远不会返回:

int parse_request(char * request, char *start, char**headers, char *body)

该函数的核心是2个嵌套的strtok():

的组合
line = strtok_r (request, "\n", &saveptr1);
while (line != NULL) {

    if (strcmp(line, "\r\n") == 0 || strcmp(line, "\r") == 0) bdy = 1;
    else {
        if (i == 1) {
            /* the first line (command) */
            printf("linea iniziale: ");
            start = line;
            start[strlen(line)] = '\0';
            printf ("%s\n",start);
            printf("\n");
        }
        else {
            if (bdy == 0) {
                /* the headers */
                temp = line;
                subline = strtok_r (temp, ":", &saveptr2);
                head = subline;
                head[strlen(subline)] = '\0';
                subline = strtok_r (NULL, ":", &saveptr2);
                if (subline != NULL) {
                    value = subline;
                    value[strlen(subline)] = '\0';
                    }
                else value = "none";

                if (strcmp(head, "Connection") == 0 && strcmp(value, "close") == 0) retval = 0;
                if (strcmp(head, "Content-Length") == 0) ignoreboby = 0;

                headers[j] = head;
                headers[j+1] = value;
                printf("header -> %s : %s\n", headers[j], headers[j+1]);
                j = j + 2;
            }
            else {
                headers[j] = '\0';
                if (ignoreboby != 1){
                    /* the body */
                    printf("body: ");
                    body = line;
                    body[strlen(line)] = '\0';
                    printf ("%s\n",body);
                }
                else {
                    body = "\0";
                    **printf("body ignored\n");**
                }
            }
        }
    }
    //printf("kkk");
    line = strtok_r (NULL, "\n", &saveptr1);
    i++;
}

程序会在打印“body ignored”或“Body:%s \ n,body”之后阻塞。

有人有想法吗?我真的很麻烦! 感谢

编辑:这可能是我创建并传递参数的真正问题吗?

char command[] = "\0", body[] = "\0";
char **headers;
headers = malloc(8192);
        if (!headers) {
            printf("Error in malloc()");
            closesocket(s);
        }
int x = parse_request(buf, command, headers, body);

1 个答案:

答案 0 :(得分:0)

那是因为你没有改变line所以你被困在while循环中。