by Dinesh Thakur Category: Puppetting On Strings

The function dstr_read given below reads a string from the keyboard into array buf, stores it in dynamically allocated memory and returns a pointer to it.

The function first reads a string from the keyboard into array buf of size 100. Then it allocates the exact memory required for this string using the malloc function and copies the string from the buffer to it. Finally, it returns a pointer to the string. As the size of buffer buf is set to 100, this function can be used to read strings such as the name of a person, email id, a line in an address, etc.

This function is used in the main function to read the first and last names of a person. Observe the calls to the free function to return to the system the memory used by strings fname and lname.


char *dstr_read(char *msg)


    char *str;

    char buf[100]; /*buffer*/

    printf("%s", msg);

    scanf("%s", buf); /*read string in buffer*/

    str = (char*) malloc(strlen(buf) + 1);

    if (str == NULL) {

       printf("Error: out of memory ...\n");



       strcpy(str, buf);

       return str;


int main ()


   char *fname, *lname;

   printf("Enter your name:\n");

   fname = dstr_read("First name : ");

   lname = dstr_read("Last name : ");

   printf("Hi, %s %s\n", fname, lname);


   free (lname);

   return 0;


        Reads a string using dynamic memory allocation for strings

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.