【问题标题】:pointers memory allocation using calloc example使用 calloc 示例的指针内存分配
【发布时间】:2013-12-21 02:44:46
【问题描述】:

当指针数组的大小本身为 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;
}

【问题讨论】:

    标签: pointers memory heap-memory calloc


    【解决方案1】:

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

    p_array[5]
    

    【讨论】:

      【解决方案2】:

      数组从零开始,所以p_array[5] 没有在您的代码中初始化。它正在打印出您系统某处的一块内存。

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

      例如:

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

      【讨论】:

      • 那个随机数是什么?
      • 我想给你另一个代码。请澄清我的疑问。#include #include int main () { int a,n; int * ptr_data; printf("请输入金额:"); scanf ("%d",&a); int arr[a]; ptr_data = (int*) malloc ( sizeof(int) ); for ( n=0; n
      • @bks4line 我刚刚运行了您的代码,这是我的解释:ptr_data 是指向您机器上特定地址的指针,因此大小始终为 8。当您使用:&ptr_data[n],您实际上是在获取 ptr_data 的基地址,然后将 n * type_size 添加到该地址。例如,&ptr_data[2] 将是 ptr_data + 2 * size_of_int 地址处的值。
      【解决方案3】:
      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] 给你一个垃圾值。

      【讨论】:

      • 这是堆中的值吗?
      • @bks4line 它不需要专门来自堆,如果该内存位置恰好在堆中,它可能是该堆位置的值,我想说的是,它只是一个值在那个特定的地址
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2015-04-21
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2022-09-24
      相关资源
      最近更新 更多