C 我的最爱!!为什么?

C 我的最爱!!为什么?,c,memory,memory-management,C,Memory,Memory Management,为什么会导致SEG故障 #include<stdio.h> #include<stdlib.h> struct node { double d; int *array; char c; }; void allocator(struct node *ptr) { int *tmp; tmp = (int*)realloc(ptr, 10); if(!tmp) {

为什么会导致SEG故障

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


 struct node 
  {
      double d;
      int *array;
      char c;
  };



  void allocator(struct node *ptr)
  {
      int *tmp;
      tmp = (int*)realloc(ptr, 10);
      if(!tmp)
      {
        ptr->array=tmp;
        ptr->array[0] = 23;
      }
  }


  int
   main()
   {
      struct node *ptr = (struct node*)malloc(sizeof(struct node));
      ptr->c = 'y';
      allocator(ptr);

      printf(" %c\n", ptr->c);      
      printf(" %d\n", ptr->array[0]);
      return 0;
   }
我的印象是,分配器函数中的realloc分配内存,而内存也映射到malloc在main中分配的内存


但这是怎么发生的呢??内存管理器不认为libstdlib在这里跟踪进程中的空闲空间和分配空间吗

为struct节点分配足够的空间,然后将其重新分配到10个字节,然后访问成员c,由于节点的结构,该成员c可能超过了第10个字节。这会导致SEG故障

此外,如果由谁来决定需要移动内存块,realloc将返回指向新位置的指针,但返回main的指针仍然指向已回收的旧块。这也可能导致SEG故障

此外,在本规范中:

int *tmp;
tmp = (int*)realloc(ptr, 10);
if(!tmp)
{
  ptr->array=tmp;
  ptr->array[0] = 23;
}
如果!tmp,您正在访问一个空指针,因为您正在将tmp分配给ptr->array,然后访问第0个元素。这也可能导致SEG故障


代码中有很多问题。您可能需要重写其中的大部分内容。

问题在于试图访问未分配的指针,这主要发生在:

printf%d\n,ptr->array[0]


分配函数为ptr分配空间,ptr是一个结构,但不为该结构中的阵列分配空间。这可能不是您打算对代码进行注释的

如果realloc移动指针,即分配器中的tmp不同于ptr,则在调用函数中,main ptr不再是有效指针。您需要将更改后的指针返回main。是的,这是真的……但我尝试重新定位int指针数组,而不是结构节点本身。。。。i、 e.reallocptr->darray,10岁左右,在it行业苦苦挣扎……只有在收到评论后才发现这个愚蠢的错误,并解决了它。无论如何,谢谢