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

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?

143k 11 11 gold badges 129 129 silver badges 204 204 bronze badges asked Nov 17, 2011 at 8:18 16.3k 24 24 gold badges 84 84 silver badges 123 123 bronze badges some of the compilers came up with these solution char a[ ] instead which is called dynamic array! Commented Nov 17, 2011 at 8:29

10 Answers 10

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 line = tmp; > /* Actually store the thing. */ line[index++] = ch; > return line; > 
answered Nov 17, 2011 at 8:20 182k 26 26 gold badges 376 376 silver badges 399 399 bronze badges

It's generally more efficient to increase the size by a multiplicative factor (ie 1.5x or double the size) unless you know that your data comes in records of a fixed size.

Commented Dec 2, 2011 at 17:31 This getln() does not return NULL at end of file. How do you check for end of file? Commented Jan 4, 2016 at 3:30 CHUNK is how many bytes to allocate. You can call it CHUNKSIZE if that makes it clearer. Commented Aug 10, 2019 at 5:18

You could have an array that starts out with 10 elements. Read input character by character. If it goes over, realloc another 5 more. Not the best, but then you can free the other space later.

answered Nov 17, 2011 at 8:21 tekknolagi tekknolagi 10.9k 26 26 gold badges 77 77 silver badges 124 124 bronze badges

In the Linux manual for vsnprintf this is exactly what they do in their example (although it's about formatting string not input, but the principle is the same.)

Commented Nov 17, 2011 at 8:24

You can also use a regular expression, for instance the following piece of code:

char *names scanf("%m[^\n]", &names) 

will get the whole line from stdin, allocating dynamically the amount of space that it takes. After that, of course, you have to free names .

answered Aug 31, 2015 at 11:06 1,097 2 2 gold badges 11 11 silver badges 33 33 bronze badges The m scanf modifier is non standard. It may or may not be supported by your C library. Commented Jan 4, 2016 at 3:33

If you ought to spare memory, read char by char and realloc each time. Performance will die, but you'll spare this 10 bytes.

Another good tradeoff is to read in a function (using a local variable) then copying. So the big buffer will be function scoped.

answered Nov 17, 2011 at 8:24 6,813 1 1 gold badge 24 24 silver badges 25 25 bronze badges

Below is the code for creating dynamic string :

void main() < char *str, c; int i = 0, j = 1; str = (char*)malloc(sizeof(char)); printf("Enter String : "); while (c != '\n') < // read the input from keyboard standard input c = getc(stdin); // re-allocate (resize) memory for character read to be stored str = (char*)realloc(str, j * sizeof(char)); // store read character by making pointer point to c str[i] = c; i++; j++; >str[i] = '\0'; // at the end append null character to mark end of string printf("\nThe entered string is : %s", str); free(str); // important step the pointer declared must be made free > 
15.9k 34 34 gold badges 118 118 silver badges 211 211 bronze badges answered Sep 22, 2014 at 12:44 Kunal Wadhwa Kunal Wadhwa 49 2 2 bronze badges

Undefined behavior because c is not initialized for first test, infinite loop and final crash on empty input file.

Commented Jan 4, 2016 at 3:24 Moreover, what about free(c)? Should also be necessary imo! Commented Feb 24, 2016 at 23:22

Here's a snippet which I wrote which performs the same functionality.

This code is similar to the one written by Kunal Wadhwa.

char *dynamicCharString() < char *str, c; int i = 0; str = (char*)malloc(1*sizeof(char)); while(c = getc(stdin),c!='\n') < str[i] = c; i++; realloc(str,i*sizeof(char)); >str[i] = '\0'; return str; > 
3 2 2 bronze badges answered Mar 31, 2018 at 11:31 161 5 5 silver badges 10 10 bronze badges

First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.

Second, use strlen to measure the exact used length of string stored before, and malloc to allocate memory in heap, whose length is defined by strlen . The code is shown below.

int strLength = strlen(strInStack); if (strLength == 0) < printf("\"strInStack\" is empty.\n"); >else < char *strInHeap = (char *)malloc((strLength+1) * sizeof(char)); strcpy(strInHeap, strInStack); >return strInHeap; 

Finally, copy the value of strInStack to strInHeap using strcpy , and return the pointer to strInHeap . The strInStack will be freed automatically because it only exits in this sub-function.