這是程序輸入從文件中一些字符串,然後推入串入LineBuf一個接一個,在我們推一個字符串轉換成LineBuf,print LineBuf,然後,製作LineBuf爲空。我調試它4小時,但我仍然無法找到BUG
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *LineBuf = NULL;
int BufLen = 0;
void PushToBuf(char c)
{
LineBuf = (char *)realloc(LineBuf, (BufLen+2)*sizeof(char));
LineBuf[BufLen] = c;
BufLen++;
LineBuf[BufLen] = '\0';
}
int main()
{
char temp[20];
int i;
FILE *fp;
fp = fopen("input", "r");
while (fgets(temp, 20, fp) > 0)
{
/*Push temp into buf*/
for (i = 0; i < strlen(temp); i++)
PushToBuf(temp[i]);
/*print buf*/
printf("%s\n", LineBuf);
printf("%d\n", BufLen);
/*make buf empty*/
free(LineBuf);
BufLen = 0;
}
return 0;
}
這是我的輸入流:
This is a test. Good evening
bye~
這是運行結果:
This is a test file
19
. Good evening
15
glibc detected ./a.out: double free or corruption (fasttop): 0x00000000023fa250
======= Backtrace: =========
/lib/libc.so.6(+0x775b6)[0x7f2ad01bf5b6]
/lib/libc.so.6(cfree+0x73)[0x7f2ad01c5e83]
./a.out[0x400868]
/lib/libc.so.6(__libc_start_main+0xfd)[0x7f2ad0166c4d]
./a.out[0x400699]
調用free() – thumbmunkeys 2011-12-17 14:45:28
後,您應該將LineBuf設置爲NULL 4小時對於查找錯誤沒有多大意義;一些錯誤會帶你4周!對於這個,'valgrind'會幫助你。 – 2011-12-17 15:12:05
@ user1103180請使用與代碼 – Ankit 2011-12-17 15:16:45