[英]Segmentation fault when calling 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);
}
謝謝您的幫助。
正如凱勒姆所說,這解決了我的問題
tmp[0] = '\0';
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.