关于realloc的问题

时间:2011-07-18 08:08:43

标签: 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上执行。

1 个答案:

答案 0 :(得分:3)

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

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