Search code examples
pointersmemoryheap-memorycalloc

pointers memory allocation using calloc example


when the size of pointer array is itself 4 and when i try to print 5th value it gives a random number.How? tell me how this random allocation happens. Thanks!

#include< stdio.h>   
#include< stdlib.h>

int main()
{
 int*    p_array;
 int i;
 // call calloc to allocate that appropriate number of bytes for the array
 p_array = (int *)calloc(4,sizeof(int));      // allocate 4 ints
 for(i=0; i < 4; i++) 
 {
  p_array[i] = 1;
 }
 for(i=0; i < 4; i++) 
 {
  printf("%d\n",p_array[i]);
 }
 printf("%d\n",p_array[5]); // when the size of pointer array is itself 4 and when i try to print 5th value it gives a random number.How?
 free(p_array);
 return 0;
}

Solution

  • Arrays start at zero, so p_array[5] wasn't initialized in your code. It is printing out a piece of memory that is somewhere on your system.

    Read this for a great description on why arrays are zero-based.

    e.g.:

    p_array[0] = 1;
    p_array[1] = 1;
    p_array[2] = 1;
    p_array[3] = 1;
    p_array[4] = 1;
    p_array[5] = ?????;