呼叫自由时的分段故障

问题描述 投票:0回答:1

我在C语言中做了一个小服务器,当我在多次连接后调用free时出现了一个segfault,但我找不到它的来源。

在开始的时候,我认为它来自于realloc,但即使它没有被调用,我也有segfault。

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

谢谢你的帮助。

c segmentation-fault malloc free
1个回答
0
投票

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

tmp[0] = '\0';

谢谢你了

© www.soinside.com 2019 - 2024. All rights reserved.