/*
 * Input (via stdin): some strings (not containing spaces) separated by newlines
 *
 * What the program does:
 * 1. the strings are appended one by one to the array inside a LIST structure;
 * 2. when the end of the input is encountered, the strings are
 *    printed in the order in which they were read.
 *
 * NOTE: if the LIST contains n strings, its capacity must also be exactly
 * n, i.e., you should never allocate storage for extra / additional strings.
 * (Of course, you would not do this in practice, but this buggy
 * program is only intended to give you some practice with gdb.)
 *
 * Tasks:
 * 1. In line 75, try both append1 and append2 functions, and fix *
 * the bugs in each case.
 * Run the program as follows: ./a.out < wordlist
 * (with small sized inputs typed by hand, you may not notice the bug).
 */


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct{
    int size;
    char **array;
}LIST;

LIST create_list(void){
    LIST l;
    l.size=0;
    l.array=NULL;
    return l;
}

void print_list(LIST L){
    int i;
    if(L.size==0)
        printf("List is empty.\n");
    else {
	printf("(%s",L.array[0]);
	for(i=1;i<L.size;i++)
            printf(", %s ",L.array[i]);
	printf(")\n");
    }
}

LIST append1(LIST L,char *a){
    L.size++;
    if(NULL==(L.array=(char**)realloc(L.array,L.size*sizeof(char*))))
    { printf("OVERFLOW..."); exit(1); }
    L.array[L.size-1]=(char*)realloc(L.array[L.size-1],9*sizeof(char));
    L.array[L.size-1]=a;
    return L;
}

LIST append2(LIST L,char *a){
    L.size++;
    if(NULL==(L.array=(char**)realloc(L.array,L.size*sizeof(char*))))
    { printf("OVERFLOW..."); exit(1); }
    L.array[L.size-1]=(char*)realloc(L.array[L.size-1],strlen(a));
    strcpy(L.array[L.size-1], a);
    return L;
}


int main()
{
    char inbuf[64];
    int i;
    LIST p;

    p=create_list();
    while (1 == scanf("%60s", inbuf))
        p=append2(p, inbuf);
    print_list(p);
    for (i = 0; i < p.size; i++)
        free(p.array[i]);
    free(p.array);

    return 0;
}


