#define _GNU_SOURCE
#include
#include
int
main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
free(line);
exit(EXIT_SUCCESS);
}
針對getline()產生的line buffer, 在最後將它free, 卻得到free(): invalid next size (fast).
最後我改用另一種寫法, 先malloc一塊夠大的buffer給line pointer, 然後, 然後就沒有error了.
len = 512;
line = malloc(len);
while( (ret = getline(&line, (size_t *)&len, fp)) != -1 ) {
if(line[0] == '#') continue; //comment
}
if(line != NULL) free(line);
沒有留言:
張貼留言