Skip to content
pramode edited this page Aug 9, 2011 · 2 revisions

Basic malloc usage

Write a C program which will read 6 strings each of maximum size 20 bytes from the keyboard; as each string is read, it should be stored in memory.

After this reading-and-storing process is over, your program should print back all the 6 strings onto the standard output.

Here is the outline:

     main()
     {
           char buf[21];
           char **p;
           int i;
           ........
           ........
     }

You should not declare any other variables (other than the three shown above) in your program. You should not change the type of any of the above 3 variables.

You have to use "malloc" to solve this problem.

Please take care to see that you always intialize pointers properly before you use them.

Freeing up the buffers allocated

To the previous program, add a function:

    void string_free(char **p, int n)
    {


    }

You will call it from "main" like this:

    main()
    {
               char **p;
               .....
               .....
               string_free(p, 6)
    }

Read the manual page of the "free" function carefully before doing this! It is very easy to get this wrong.

The "realloc" and "calloc" functions

Read the manual page of the "realloc" and "calloc" functions and write two test programs which demonstrate the use of these functions.

The "strtok" function

Read the manual page of the strtok function and write a program which demonstrates its use.

The "sprintf" function

Read the manual page of the "sprintf" function and write a program which demonstrates its use.

More functions:

Repeat the above exercise for these C functions:

      strstr, rindex, strtol, strncmp, strncasecmp,