简体   繁体   English

在 C 中不使用 malloc 将局部变量保存在堆上(使用 sbrk 或 brk)

[英]Save a local variable on a heap without using malloc in C (using sbrk or brk)

I have a struct as follows:我有一个结构如下:

struct 
  __attribute__((__packed__)) // compiler directive, avoid "gcc" padding bytes to struct
  meta_data {
    size_t size;             // 8 bytes (in 64-bit OS)
    char free;               // 1 byte ('f' or 'o')
};

The size of the struct is 9 bytes.该结构的大小为 9 个字节。

I want to use sbrk or brk to allocate 9 bytes on the heap and save a struct on the heap, and return a pointer to the dynamically allocated memory block on heap.我想使用 sbrk 或 brk 在堆上分配 9 个字节并在堆上保存一个结构,并返回指向堆上动态分配的 memory 块的指针。

Currently I have something like this:目前我有这样的事情:

void *add(size_t size) {
  void* returnPointer;
  returnPointer = sbrk(9);
  struct meta_data newMetadata;
  newMetadata.size = size;
  newMetadata.free = 'o';
  return returnPointer;
}

This function should be able to be used multiple times to add more metadata blocks on the heap.这个 function 应该可以多次使用,以在堆上添加更多元数据块。

However, in this case, when the function ends, the local variable newMetadata declared inside the function is also terminated.但是,在这种情况下,当function结束时,function内部声明的局部变量newMetadata也被终止。

How can I keep it on the heap and not lose access to the newMetadata created?我怎样才能将它保留在堆上而不失去对创建的新元数据的访问权限?

Note: I am not allowed to use malloc for this.注意:我不允许为此使用 malloc。

The usual method is to mimic what some malloc packages do.通常的方法是模仿一些malloc包的作用。 That is, put the meta data at a lower address than what is returned as the "data" pointer.也就是说,将元数据放在比作为“数据”指针返回的地址更低的地址。

Here's your code refactored to do that:这是您重构的代码以执行此操作:

#include <unistd.h>

struct meta_data {
    size_t size;                        // 8 bytes (in 64-bit OS)
    char free;                          // 1 byte ('f' or 'o')
// compiler directive, avoid "gcc" padding bytes to struct
} __attribute__ ((__packed__));

void *
add(size_t size)
{
    struct meta_data *meta;
    void *returnPointer;

    meta = sbrk(sizeof(struct meta_data) + size);
    meta->size = size;
    meta->free = 'o';

    returnPointer = meta;
    returnPointer += sizeof(struct meta_data);

    return returnPointer;
}

Note that most malloc replacements will guarantee that returnPointer is "aligned for any purpose", which usually means aligned to an 8 byte boundary (ie the lower 3 bits of returnPointer are 0).请注意,大多数malloc替换将保证returnPointer是“出于任何目的对齐”,这通常意味着对齐到 8 字节边界(即returnPointer的低 3 位为 0)。

The above code doesn't do that, so it's something you can add [later].上面的代码没有这样做,所以你可以 [later] 添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM