#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void my_strcat(char **str, char **buf)
{
    char *ptr;
    int n;
    int len;

    /* 終端の\nを消す */
    len = strlen(*str);
    if (len) {
        ptr = *str + len - 1;
        if (*ptr == '\n') {
            *ptr = '\0';
        }
    }
    len = strlen(*buf);
    if (len) {
        ptr = *buf + len - 1;
        if (*ptr == '\n') {
            *ptr = '\0';
        }
    }

    /* strとbuf分の領域確保 */
    n = strlen(*str) + strlen(*buf);
    ptr = (char *) realloc(*str, n + 1);
    if (ptr == NULL) {
        /* exit();するのでfree不要
           free(*str);
           free(*buf);
         */
        exit(1);
    }
    *str = ptr;

    /* bufをstrに結合する */
    if (n) {
        strcat(*str, *buf);
    }

    return;
}

int main(void)
{
    int n;
    char *str, *buf;

    /* 確保・初期化 */
    if (NULL == (str = (char *) malloc(30 * sizeof(char)))) {
        exit(1);
    }
    if (NULL == (buf = (char *) malloc(30 * sizeof(char)))) {
        exit(1);
    }
    *str = '\0';

    /* 入力、連結 */
    for (n = 1;; ++n) {
        printf("input string_%d :", n);
        fgets(buf, 30, stdin);
        if (strcmp(buf, "quit\n") == 0) {
            /* quitと入力されたらループを抜ける */
            break;
        }
        my_strcat(&str, &buf);
    }

    /* 表示 */
    printf("str = %s\n", str);

    /* 終了 */
    free(str);
    free(buf);
    return 0;
}
