Emulating C++ string input in C I did the following exercise:


  Write a C program that does the equivalent of C++ string s; cin&gt;&gt;s;; that is, define an input operation that reads an arbitrarily long sequence of whitespace-terminated characters into a zero terminated array of chars.


I wonder if it's good code. What could be improved? 

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;ctype.h&gt;

struct String {
    char* signs;
    size_t size;
    size_t capacity;
};

void String_allocate_space(char **c, size_t *capacity)
{
    if (*capacity == 0) {   // allocate the first time
        *capacity = 1;
        *c = malloc(sizeof(**c) * ((*capacity)));
    }
    else {
        *capacity *= 2;     // double the new capacity
        *c = realloc(*c, sizeof(**c) * (*capacity));
    }
    if (*c == NULL)
        exit(-1);
}

void add_character(struct String* string, int ch)
{
    if (string-&gt;size == string-&gt;capacity) {     // if current letter sz = capacity
        String_allocate_space(&amp;string-&gt;signs, &amp;string-&gt;capacity);
    }
    string-&gt;signs[string-&gt;size++] = ch;    // append the sign in the array
}

void String_read(struct String* string)
{
    int ch = ' ';
    while (ch = getc(stdin)) {

        if (!isalpha(ch))
            break;

        add_character(string, ch);
    }
    add_character(string, '\0');
}

void String_print(struct String* string)
{
    printf("%s", string-&gt;signs);
}

void String_free(struct String* string)
{
    int i = 0;
    for (i = 0; i &lt; string-&gt;capacity; ++i) {
        free(string[i].signs);
        string[i].signs = NULL;
    }
}

int main()
{
    struct String string = { 0 };

    String_read(&amp;string);
    String_print(&amp;string);
    String_free(&amp;string);

    getchar();
    return 0;
}
Don't do this:
*c = realloc(*c, sizeof(**c) * (*capacity));

Once you have error handling that's more sophisticated than exit(1), this will become a liability.  You need a temporary:
char *tmp = realloc(*c, new_capacity);
if (!tmp) {
    /* error handling - c is still valid */
    /* ... */
}
*c = tmp;
*capacity = new_capacity;


If you always initialize the data pointer to start as a null pointer, you don't need to use malloc() instead of realloc().  String_allocate_space would be easier to write if it accepts a pointer to a struct String; that makes it closer to the object-oriented version:
void String_init(struct String* string)
{
    string-&gt;data = NULL;
    string-&gt;size = string-&gt;capacity = 0;
}

void String_allocate_space(struct String* string)
{
    size_t new_capacity = string-&gt;capacity ? 2 * string-&gt;capacity : 16;
    char *tmp = realloc(string-&gt;data, new_capacity);
    if (!tmp) {
        /* error handling - c is still valid */
        exit(1);                /* TODO: improve error reporting */
    }
    string-&gt;data = tmp;
    string-&gt;capacity = new_capacity;
}

I've also incorporated a change above to start with a larger initial size (16) instead of 1.  That lets us skip the first 4 reallocations for free.

The read() method has a flaw that will become apparent when you try to read another value into a string - unlike std::string, reading with &gt;&gt; will append to it, instead of replacing it.  We need to reset size at the beginning:
void String_read(struct String* string)
{
    string-&gt;size = 0;
    int ch;
    while (ch = getc(stdin)) {

        if (!isalpha(ch))
            break;

        add_character(string, ch);
    }
    add_character(string, '\0');
}

Also, the logic is slightly wrong - we want to finish when we see a space, rather than any non-alpha (which could be digits or punctuation characters).  (Well done for remembering that getch() returns int rather than char - that's one common error avoided).
void String_read(struct String* string)
{
    string-&gt;size = 0;
    int ch;
    while ((ch = getc(stdin)) != EOF &amp;&amp; !isspace(ch)) {
        add_character(string, (char)ch);
    }
    add_character(string, '\0');
}


When we free the string, we don't need a loop.  Instead, we have a single free().  It's a good idea to reset the size and capacity so that the string object is consistent - it can be used again and/or freed again without harm:
void String_free(struct String* string)
{
    free(string-&gt;data);
    string-&gt;data = NULL;
    string-&gt;size = string-&gt;capacity = 0;
}

This is an important concept in object-oriented programming - objects have invariants that they guarantee are true at the start and end of every (public) operation.  In this case, the invariants are that

data points to valid storage of at least capacity if capacity &gt; 0 and is a null pointer otherwise.
size is not greater than capacity.


We can improve the printing so that it outputs any embedded NUL characters, just like C++ strings do:
void String_print(struct String* string)
{
    if (fwrite(string-&gt;data, 1, string-&gt;size, stdout) != string-&gt;size) {
        exit(1);                /* TODO: improve error reporting */
    }
}

Note that this will now print the trailing NUL we added.  We no longer need that to mark the end of string, so we can remove that line.

Modified code
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;ctype.h&gt;

struct String {
    char* data;
    size_t size;
    size_t capacity;
};

void String_init(struct String* string)
{
    string-&gt;data = NULL;
    string-&gt;size = string-&gt;capacity = 0;
}

void String_allocate_space(struct String* string)
{
    size_t new_capacity = string-&gt;capacity ? 2 * string-&gt;capacity : 1;
    char *tmp = realloc(string-&gt;data, new_capacity);
    if (!tmp) {
        /* error handling - c is still valid */
        exit(1);                /* TODO: improve error reporting */
    }
    string-&gt;data = tmp;
    string-&gt;capacity = new_capacity;
}

void add_character(struct String* string, char ch)
{
    if (string-&gt;size == string-&gt;capacity) {     // if current letter exceeds capacity
        String_allocate_space(string);
    }
    string-&gt;data[string-&gt;size++] = ch;    // append it
}

void String_read(struct String* string)
{
    string-&gt;size = 0;
    int ch;
    while ((ch = getc(stdin)) != EOF &amp;&amp; !isspace(ch)) {
        add_character(string, (char)ch);
    }
}

void String_print(struct String *restrict string, FILE *restrict stream)
{
    if (fwrite(string-&gt;data, 1, string-&gt;size, stream) != string-&gt;size) {
        exit(1);                /* TODO: improve error reporting */
    }
}

void String_free(struct String* string)
{
    free(string-&gt;data);
    string-&gt;data = NULL;
    string-&gt;size = string-&gt;capacity = 0;
}

int main()
{
    struct String string;

    String_init(&amp;string);
    String_read(&amp;string);
    String_print(&amp;string, stdout);
    String_free(&amp;string);
}