Day#57 'C' Coding Challenge

Day#57 'C' Coding Challenge

What could be improved in the below code?

#include <stdio.h> void main() { int data = 10; int count, *ptr; ptr = (int *) malloc(data*sizeof(int)); for(count = 0; count < data; count++) { printf("%d\n", (ptr+count)); printf("%d\n", *(ptr+count)); } }

---------------------------------------------------------------

The above code has data variable assigned to 10
A counter and a pointer has been declared.

The below statement allocates memory using malloc() for the 10 numbers assigned to data. Each variable has memory allocated equal to size of the int. This statements returns the pointer to the starting address of the memory.

ptr = (int *) malloc(data*sizeof(int));

The for loop tries to print the address of the pointers using the below statement.

printf("%d\n", (ptr+count));

The for loop tries to print the data using the below statement. As the data to be stored inside the memory is not initialized, it prints garbage.

printf("%d\n", (ptr+count));

This can be improved further as mentioned below:
  • Once the memory is allocated using malloc(), is it better to check if the memory is assigned properly or not. This can be done using below statement.
           if(ptr!=NULL)
            {
                // perform required operations
            }
            else
            {
                // return error saying memory is not allocated
            }
  • After allocating memory use free(ptr) function to free up the space
  • In the above program we have used without initializing the memory, so, garbage value is returned. We have to assign data.
Few more points for malloc() function:
  • Assigns garbage value to data in the memory
  • return type of malloc() is void type. So, type casting shall be done to assign to a pointer of specific type
  • if the memory is not sufficient or not allocated properly due to any other reason, NULL shall be returned
  • Allocates a block of memory

Post a Comment

0 Comments