Hi I'm trying to write a simple version of the tail program in linux, but I keep getting a seg fault when I run the program. I wrote a simpler version but with fixed number of lines to print and using
char lines[10][100];
instead of
char **lines;
and it was working fine.
I have the program reading form stdin for the moment and i will add the ability for n to be choosen from the command line
If anyone can point out where i'm going wrong i would really appreciate it.
Thank you again.
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define MAXLINE 100
void allocate2d( char **p,int x,int y);
int i = 0;
int j = 0;
char **lines;
int main(void) {
int n = 10;
allocate2d(lines,n,MAXLINE);
while(fgets(lines[i],100,stdin)) {
++i;
i %= n;
}
--i;
for(j= 0;j<= n;j++) {
printf("%s",lines[i]);
++i;
i %= n;
}
return 0;
}
void allocate2d(char **p,int x,int y) {
int i = 0;
printf("%d\n",sizeof(*p));
p = (char **) malloc(x*sizeof(*p));
if(p != NULL) {
for (i = 0;i <= x; i++) {
if(!(p[i] = (char*) malloc(y*sizeof(char)))) {
perror("Malloc");
exit(-1);
}
}
}
else {
perror("Maloc");
exit(-1);
}
}