Gabson
Gabson

Reputation: 431

how to use a static struc into a static function ? ( like a global )

for the need of my project i need to handle a global (representing the heap ). It's a C project, i don't have any errors at the compilation.

but when i try to use a member of struct -> segfault.

if someone could tell me where is the point ?

thanks

static t_meta   *init_get_meta()
{
  static t_meta *allineed = NULL;
  int           i;

  i = 0;
  if (allineed == NULL)
    {

      //allineed->pagesize = getpagesize();                                                                                         
      //allineed->pagesize = 4096;                                                                                                  
      allineed->pagesize = 0; --> segfault right here
      printf("LOVE\n");
      while (i < 8)
        {
          allineed->listfree[i++] = NULL;
        }
      allineed->last = extend_heap(allineed);
    }
  return (allineed);
}

Upvotes: 0

Views: 83

Answers (1)

cmidi
cmidi

Reputation: 2020

You are de-referencing a NULL pointer. Here in this line of code you check for NULL and go ahead and access that memory which is illegal.

if (allineed == NULL)
     allineed->pagesize = 0; // incorrect at this time allineed is pointing to 0x0

What you need to do is malloc the structure and than check if malloc returned with not a NULL value. something on the lines of

static t_meta *allineed = malloc(sizeof(t_meta));
if (allineed)
{
    //do something
}
else
   //return error

You might want to look at these questions if you are trying to implement a basic malloc yourself

How do malloc() and free() work?

How is malloc() implemented internally?

A very basic malloc would do these basic steps

void * my_malloc(size_t size) 
{
    size_t headersize = 1; // 1 byte header
    uint8_t alignment = 8; // 8 byte alignment
    // the block should be 8 bytes align
    size_t alloc_size = ((size+1)+(alignment-1))&~(alignment-1);
    //use system call 
    void *head = sbrk(alloc_size );
    if(head == (void *)(-1))
        return NULL;
    //update the header here to mark the size and other bits depending upon req
    char *header_val = (char *)head;
    *header_val = (alloc_size/2) | ( 1 << 7);//only support power 2 sizes 
    //return updated pointer location to point to ahead of header
    // after changing the pointer to char type as pointer arithmetic is not allowed on void pointers
    //printf("allocated size is %d with first byte %p\n",alloc_size,header_val);
    //printf(" %02x\n",(unsigned char)*(char *)header_val);

    return (char *)head + headersize;
}

Upvotes: 2

Related Questions