免费通话时出现分段错误

时间:2020-05-01 23:16:39

标签: c segmentation-fault malloc free

我用c做一个小服务器。 当我在多次连接后拨打免费电话时遇到段错误,但我无法确定它的来源。

一开始我以为它来自realloc,但是即使它没有被调用,我也有段错误。

for (;;) {
        if ((client = accept(sock, NULL, NULL)) < 0) {
            err(EXIT_FAILURE, "Failed to accept client");
        }

        totalBytes = 0;
        int size = 2048;

        char* tmp = malloc(sizeof(char) * size);

        if (tmp == NULL) {
            err(EXIT_FAILURE, "Failed to malloc");
        }

        while ((r = read(client, buffer, BUFFER_SIZE)) > 0) {
            totalBytes += r;

            if (totalBytes >= size) {
                size += totalBytes - size + 1;
                tmp = realloc(tmp, sizeof(char) * size);

                if (tmp == NULL) {
                    err(EXIT_FAILURE, "Failed to realloc");
                }
            }

            buffer[r] = '\0';
            strcat(tmp, buffer);

            ioctl(client, FIONREAD, &r);

            if (r <= 0) {
                break;
            }
        }

        char http_request[size];

        strcpy(http_request, tmp);
        free(tmp);
}

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

正如kaylum所说,这解决了我的问题

tmp[0] = '\0';

谢谢

相关问题