c - 关于重新分配的问题

标签 c memory memory-management

在下面的程序中,realloc分配的地址落在malloc分配的地址范围内。我不明白为什么。 (请忽略内存的释放。)

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


   struct MyClass 
   {
      double num;
   };

   struct node
   {
      MyClass* array;
      int max_size;
      double w[10]; //used only to increase the size of node
      long double ld;
   };




  void fill(struct node *ptr)
  {
      MyClass *tmp;

      if(ptr->array==NULL )
         tmp = (MyClass*)realloc(ptr->array, 10*sizeof(MyClass) );

         printf("addr range of node: %p  <-->  %p\n", ptr, &(ptr->ld));
         printf("addr recvd by tmp: %p\n", tmp);
      if(tmp)
      {
        ptr->array=tmp;
        ptr->array[0].num=32.23;
        ptr->ld = 33.1321;
      }
  }


 struct node*
   allocator()
      {
         struct node* ptr =(struct node*)malloc(sizeof(struct node*));
         ptr->max_size= 232;
         ptr->ld =321.3425;
         ptr->array = __null;
         return ptr;
      }

  int
   main()
   {
      struct node *ptr =allocator();
      fill(ptr);
      printf(" %Lf  %lf\n", ptr->ld, ptr->array[0].num);  
      return 0;
   }

输出:

addr range of node: 0xa2a010  <-->  0xa2a070

addr recvd by tmp: 0xa2a030

 33.132100  32.230000

在 x64 Linux 上执行。

最佳答案

结构节点* ptr =(结构节点*)malloc(sizeof(结构节点*));

应该是struct node* ptr =(struct node*)malloc(sizeof(struct node));

关于c - 关于重新分配的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730171/

相关文章:

c - 线程连接中的 TERMINATED 消息

memory - 不可撤销的页面

c - 在动态分配的二维数组上使用 realloc() 是个好主意吗?

linux - Kubernetes Pod 报告的内存使用量多于实际进程消耗量

c - 当在堆上请求大块内存时,如果 RAM 上没有连续空间,是否在磁盘上分配(交换)?

C - 检查字符串是否是另一个字符串的子字符串

arrays - 在c中的冒泡排序中获得不同的输出

十六进制 float 表示的计算值

memory - 虚拟内存

ios - 如何在 viewController 转换期间释放内存