I was working on an exercise in C and came across a very strange thing. The program is supposed to take input and put it into an array. (It's also supposed to check if the line is >80 characters long, but that's not implemented yet and isn't involved in the problem.) The initial problem was that each new line overwrites the previous. My attempt to fix this resulted in a bug where nothing was output.
The original function that copies a single line is:
void copy(void)
{
int i;
extern char line[], storage[];
i = 0;
while ((storage[i] = line[i]) != '\0')
i++;
}
line
contains the source string with \0 at the end. storage
is where it is stored after. Each time copy
is called, the new value in line
overwrites the value in storage
.
I tried adding another index (named curend
) to copy()
to track the position in storage
between calls (see full sample code below), which would point to right after the previous string, and then increment that index in copy()
's while
loop. After this change, copy()
seemingly just stops saving anything into storage
. It compiles and runs without warnings or error. Why is this happening?
/* The purpose of the program is to take an input
of a string, check if it's >80 characters long
and put it into storage[]. Then repeat until
the input is EOF. And print what's in storage as 1 string */
#include <stdio.h>
#define MAXLEN 1000 // maximum length a line can be
#define REQLEN 3 // length required to pass the check
// right not is set to 3 for testing
#define MAXSTOR 1000000
int curend = 0; // current end of the previous line
int len; // global length
char line[MAXLEN];
char storage[MAXSTOR];
/* The issue occurs here. It seems to not write anything into storage[] at all. */
void copy(void)
{
int i;
extern int curend;
extern char line[], storage[];
i = 0;
while ((storage[curend] = line[i]) != '\0')
i++;
curend++; // this line is added
storage[curend] = '\n';
curend++;
}
int getlines(void)
{
int c, i;
extern char line[];
for (i = 0; i < MAXLEN-1
&& (c=getchar()) != EOF && c != '\n'; i++)
line[i] = c;
if (c == '\n' ) {
line[i] = c;
i++;
}
line[i] = '\0';
return i;
}
int main()
{
extern int len;
extern char storage[];
while ((len = getlines()) > 0)
if (len > REQLEN)
copy();
storage[curend] = '\0';
printf("%s", storage);
}