求助:实现linux下的tail程序,程序报"Segmentation fault"
程序要求:写一个简易的tail程序。命令行格式是tail -n, 将输出最后的n行,如果不加参数,默认输出最后的10行.
现在是程序可以实现功能,但会报错:
Segmentation fault.
编程环境:
debian linux
kernel 2.6.32.5
gcc version 4.4.5
代码如下:
程序代码:
#include <stdio.h> #include <string.h> #include <ctype.h> #define MAXLINES 5000 #define MAXLEN 1000 #define ALLOCSIZE 10000 char *lineptr[MAXLINES]; static char allocbuf[ALLOCSIZE]; static char *allocp = allocbuf; char *alloc(int n) { if (allocbuf + ALLOCSIZE - allocp >= n) { allocp += n; return allocp - n; } else return 0; } int getl(char *s, int lim) { int c, i; for (i = 0; i<lim-1 && (c=getchar()) != EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = getl(line, MAXLEN)) > 0) if (nlines >= maxlines || (p = alloc(len)) == NULL) return -1; else { line[len-1] = '\0'; strcpy(p, line); lineptr[nlines++] = p; } return nlines; } void writelines(char *lineptr[], int nlines, int lastlines) { int i; for (i = nlines - lastlines; i <= nlines; ++i) printf("%s\n", lineptr[i]); } main(int argc, char *argv[]) { int nlines, i, n; if (argc == 2 && (*++argv)[0] == '-') { for (i = 1; (*argv)[i] != '\0'; ++i) { if (!isdigit((*argv)[i])) { printf("error format 1.\n"); return -1; } } n = atoi(&(*argv)[1]); } else if (argc == 1) n = 10; else printf("error format 2.\n"); if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { writelines(lineptr, nlines, n); return 0; } else { printf("error: input too big to print\n"); return 1; } }
==================================================
test是测试文件.
程序运行的输出如下:
程序代码:
xls@Debian:~/debian/code/c_programs$ cc 5-13.c -o tail1 xls@Debian:~/debian/code/c_programs$ cat test 11111111111111111111111111 2222222222222222222222222222 33333333333333333333333 444444444444444444444444444444444444 55555555555555555555 666666666666666666666666666666666 77777777777777777777777777777777777777777777777777777 88888888888888888888888888888 999999999999999 1010101010101010010101010101010 11 11 11 11 11 12 12 12 12 12 13 13 13 13 14 14 14 14 14 14 14 15 15 15 15 15 15 15 15 xls@Debian:~/debian/code/c_programs$ a.out -3 < test 13 13 13 13 14 14 14 14 14 14 14 15 15 15 15 15 15 15 15 Segmentation fault xls@Debian:~/debian/code/c_programs$
请大家帮忙看一下为什么会有这个报错呢?