1

I found something rather strange while I was working at a school project that I have to write in C

Here is the example you cand find for using the calloc function in C

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

int main()
{
  int i, n;
  int *a;

  printf("Number of elements to be entered:");
  scanf("%d",&n);

  a = (int*)calloc(n, sizeof(int));
  printf("Enter %d numbers:\n",n);
  for( i=0 ; i < n ; i++ ) 
  {
   scanf("%d",&a[i]);
  }

  printf("The numbers entered are: ");
  for( i=0 ; i < n+4 ; i++ ) { // This is the line I want you to look at
   printf("%d ",a[i]);
  }

  return(0);
  }

This works just fine even if it shouldn't[or at least I think so].Even though I allocate only an array of n elements it prints out n+4 elements when I ask him to[mostly 0].

Is there an explanation to this?

PS:I am working on a linuxMint 16 right now if this makes any difference

tudoricc
  • 709
  • 1
  • 12
  • 31

0 Answers0