Could you explain following code?
str = (char *) malloc (sizeof(char) * (num+1));
malloc doing here?
Malloc in this case is allocating num+1 times sizeof(char) bytes. This is standard practice when you want to allocate an array of elements. The char in sizeof(char) is typically replaced with the type of array being allocated.
Strictly speaking in this example though the sizeof(char) is not necessary. It's guaranteed to be of size 1 by the C standard and hence just multiplying by 1.