使用calloc示例指针内存分配

时间:2013-12-04 14:45:46

标签: pointers memory heap calloc

当指针数组的大小本身为4时,当我尝试打印第5个值时,它会给出一个随机数。如何?告诉我这个随机分配是如何发生的。谢谢!

#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 个答案:

答案 0 :(得分:0)

以下内容为undefined behaviour,因为您正在读取数组的末尾:

p_array[5]

答案 1 :(得分:0)

数组从零开始,因此代码中未初始化p_array[5]。它打印出系统中某处的内存。

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

答案 2 :(得分:0)

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

是尝试打印未初始化的内存部分,因为您的数组p_array具有仅存储5个p_array = (int *)calloc(4,sizeof(int));项的强度 p_array[0]p_array[4]因此p_array[5]会为您提供垃圾值。