【问题标题】:how to use a static struc into a static function ? ( like a global )如何将静态结构用于静态函数? (像一个全球性的)
【发布时间】:2015-02-10 23:32:06
【问题描述】:

为了我的项目的需要,我需要处理一个全局(代表堆)。这是一个C项目,我在编译时没有任何错误。

但是当我尝试使用 struct -> segfault 的成员时。

如果有人能告诉我重点在哪里?

谢谢

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);
}

【问题讨论】:

  • 你没有 malloc...你引用了一个 NULL 值
  • 我想,你们投了反对票,因为我没有解释我正在编写 malloc 函数,现在我不明白我必须使用 sbrk 谢谢

标签: c list struct static


【解决方案1】:

您正在取消引用 NULL 指针。 在这行代码中,您检查 NULL 并继续访问非法的内存。

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

你需要做的是 malloc 结构,然后检查 malloc 返回的不是 NULL 值。

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

如果你想自己实现一个基本的 malloc,你可能想看看这些问题

How do malloc() and free() work?

How is malloc() implemented internally?

一个非常基本的 malloc 会完成这些基本步骤

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;
}

【讨论】:

  • 其实我正在编写一个malloc函数,所以我不能使用它。
  • 没关系,但关键是你不能访问你没有分配的内存,你需要在堆栈上分配内存,通过使用 malloc ,通过使用 OS 共享内存通过 mmap 或 shmget。你可能想看看这个问题stackoverflow.com/questions/3479330/…
猜你喜欢
  • 2015-07-02
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
相关资源
最近更新 更多