pointers memory allocation using calloc example

329 views Asked by At

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;
}
3

There are 3 answers

3
Matt On BEST ANSWER

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] = ?????;
0
NPE On

The following has undefined behaviour since you're reading past the end of the array:

p_array[5]
2
manish On
printf("%d\n",p_array[5]);

is an attempt to print an uninitialized section of memory, because your array p_array has the strenght to store only 5 items p_array = (int *)calloc(4,sizeof(int)); starting from p_array[0] through p_array[4] and hence p_array[5] gives you a garbage value.