c - 如何将静态结构用于静态函数? (像一个全局)

标签 c list struct static

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

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

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

谢谢

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

最佳答案

您正在取消引用 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;
}

关于c - 如何将静态结构用于静态函数? (像一个全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443911/

相关文章:

Python:ctypes + C malloc 错误。 C内存问题还是Python/ctypes问题?

python - Python 中使用不同分隔符连接列表

c++ - Arduino/C++ : Access specific header file of structs from library

c - C 中包含 char 数组成员的结构 - 范围不正确

c - 如何使用节点指针建立链表解决赋值中的不兼容类型

c - Check Sum 函数 C 中的段错误

c++ - 查找由链表链接的数据的各个地址。 C++

c++ - 访问结构中定义的枚举值

c - 为什么 strlen 函数在没有 #include<string.h> 的情况下也能工作?

java - 表示java中的常量列表