这是程序输入从文件中一些字符串,然后推入串入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