开发者

My fav Segfault!! why?

why this,causes a segfault??

#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)
      {
      开发者_如何学JAVA  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;
   }

i got an impression as if the realloc() in the allocator function allocates memory which also maps to the memory allocated by malloc() in the main..

but how does this could happen?? Doesn't the memory manager(i guess the lib(stdlib) here) keeps track of free and allocated spaces in a process??


You're allocating space enough for a struct node then reallocating it to 10 bytes, then accessing the member c which, due to the structure of node, is probably past the 10th byte. This causes a segfault.

Also, if whoever's business it is to decide decides that it needs to move the memory block, realloc returns a pointer to the new location but the pointer back in main still points to the old block which has been reclaimed. This could also cause a segfault.

Also, in this code:

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

if !tmp, you're accessing a NULL pointer because you're assigning tmp to ptr->array then accessing the 0th element. This could also cause a segfault.

There are many problems in your code. You may need to rewrite much of it.


The problem with this is the attempt to access an unallocated pointer, which happens in main:

printf(" %d\n", ptr->array[0]);

Your allocation function assigns space for ptr, which is a structure, but not for the array within that structure. Possibly this is not what you intended to do (comment your code!).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜