简体   繁体   English

免费调用时出现分段错误

[英]Segmentation fault when calling free

I making a little server in c.我在 c 中制作了一个小服务器。 I have a segfault when i call free after multiple connections but i can't find out where it come from.当我在多次连接后免费调用时出现段错误,但我无法找出它来自哪里。

At the beginning i thought it came from realloc but even when it is not called i have the segfault.一开始我以为它来自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);
}

Thank you for your help.谢谢您的帮助。

As kaylum said, this solve my problem正如凯勒姆所说,这解决了我的问题

tmp[0] = '\0';

Thank you谢谢

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

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