I have a problem with exercise 5-13 of K&R, the goal of the exercise is to make a function tail that does the same as the *nix command, here's my function:
#include <stdio.h>
#include <string.h>
#include "tail.h"
int tail(int n)
{
char *saved_lines[n];
for (int i = 0; i < n; i++)
saved_lines[i] = "\0";
int line_state[n];
for (int j = 0; j < n; j++)
line_state[j] = 0;
int num_lines = 0, i = 0;
char line[MAXLINE];
saved_lines[n - 1] = "\0";
while (get_line(line, MAXLINE) > 0)
{
for (i = 0; i < n - 1; i++)
{
strcpy(saved_lines[i], saved_lines[i + 1]);
line_state[i] = line_state[i + 1];
}
strcpy(saved_lines[n - 1], line);
line_state[n - 1] = 1;
}
printf("last %d lines: \n", n);
for (i = 0; i < n; i++)
if (line_state[i] == 1)
printf("%d: %s\n", i, saved_lines[i]);
}
problem is when I run it I get a Segmentation fault (core dumped)
error, and running it through Valgrind shows the error comes from the call to strcpy
:
==25284== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==25284== Bad permissions for mapped region at address 0x108E64
...I don't get why, at first strcpy
had a problem with the saved_lines[i]
pointers being non initialized, fixing that with
for(int i=0;i<n;i++)
saved_lines[i]="\0";
didn't help...any ideas what could cause this ? thanks in advance!
EDIT: initiated --> initialized