这是程序从一个文件中输入一些字符串,然后,将字符串一个一个地推入LineBuf中,我们将一个字符串推入LineBuf后,打印LineBuf,然后将LineBuf 设为空。
这是我的代码:
#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]