【问题标题】:Question regarding realloc [closed]关于 realloc 的问题 [关闭]
【发布时间】:2011-07-18 08:08:43
【问题描述】:

在下面的程序中,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 上执行。

【问题讨论】:

  • 这不是plz find error in the program 网站。
  • -1,至少尝试自己诊断问题(使用调试器等工具,甚至在这里或那里使用不起眼的打印语句) - 纯粹的懒惰......
  • 我认为这是一个有效的问题。

标签: c memory memory-management


【解决方案1】:

struct node* ptr =(struct node*)malloc(sizeof(struct node*));

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

【讨论】:

  • 非常感谢你拯救了我的一天.. :)
猜你喜欢
  • 2015-07-08
  • 2023-03-23
  • 1970-01-01
  • 2011-10-17
  • 2013-05-13
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
相关资源
最近更新 更多