Rahul Bhatia
Rahul Bhatia

Reputation: 1

Garbage Value in Calloc in the last memory block

main()
{
  int *p;
  p = calloc(5,2);
  int i;
  for(i=0;i<5;i++){
    printf("%d ",*(p+i));
  }
}

Why is the output giving a garbage value in the last memory block when calloc sets the memory of all the blocks by default to zero?

Upvotes: 0

Views: 210

Answers (1)

Honza Dejdar
Honza Dejdar

Reputation: 957

You should use calloc(5, sizeof(int)). You allocated 5 x 2 bytes, but int is usually 4 bytes large. Using sizeof() is a good practice due to portability.

Upvotes: 1

Related Questions