How to dynamically allocate memory space for a string and get that string from user?

Dinesh picture Dinesh · Nov 17, 2011 · Viewed 146.4k times · Source

I want to read input from user using C program. I don't want to use array like,

char names[50];

because if the user gives string of length 10, then the remaining spaces are wasted.

If I use character pointer like,

char *names;

then I need to allocate memory for that in such a way of,

names = (char *)malloc(20 * sizeof(char));

In this case also, there is a possibility of memory wastage.

So, what I need is to dynamically allocate memory for a string which is of exactly same as the length of the string.

Lets assume,

If the user input is "stackoverflow", then the memory allocated should be of 14 (i.e. Length of the string = 13 and 1 additional space for '\0').

How could I achieve this?

Answer

cnicutar picture cnicutar · Nov 17, 2011

Read one character at a time (using getc(stdin)) and grow the string (realloc) as you go.

Here's a function I wrote some time ago. Note it's intended only for text input.

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);

        /* Check if we need to stop. */
        if (ch == EOF || ch == '\n')
            ch = 0;

        /* Check if we need to expand. */
        if (size <= index) {
            size += CHUNK;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }

        /* Actually store the thing. */
        line[index++] = ch;
    }

    return line;
}