C 将动态分配的结构收缩为结构中的单个元素

问题描述 投票:0回答:1

在优化我的代码时,我注意到我调用 malloc 的频率太高。具体来说,我释放了一个结构,然后使用相同的值重新分配了我释放的结构中的相同元素。

最好用代码来展示:

#include <stdlib.h>

struct someStruct
{
    int x, y, z;
    float w;
};

struct node
{
    struct node *prev, *next;
    struct someStruct value;
};

struct someStruct* extract(struct node* old)
{
    struct someStruct *value = (struct someStruct*)malloc(sizeof(struct someStruct));
    *value = old->value;
    free(old);
    return value;
}

我不想在提取函数中使用malloc。 我只想释放“上一个和下一个”,例如:

内存布局:

Some_addr:
# prev
# next
# value

return_addr = extract(some_addr);

Some_addr:
# // made free (prev)
# // made free (next)
return_addr:
# value

注意:我使用的是 Windows 64x

上面的代码简化自的真实代码:(是C++)

namespace Lists
{
    template <typename T>
    struct Node
    {
        Node* next;
        T value;
    };
}

struct Node
{
   Node* parent;
   void* data;
   uint8_t kind;

   inline Lexer::Token* get_token() const
   {
        return reinterpret_cast<Lexer::Token*>(data);
   }

   Node(Node* parent, const Lexer::Token& token)
         : parent(parent)
         , kind(kinds::token)
   {
         allocvs(Lexer::Token, data, 1); // custom malloc that increases some x value where x for checking memory leaks after code has exit
         *get_token() = token;
    }

   Node(Lists::List<Lexer::Token>& tokens)
      : parent(NULL)
      , kind(kinds::list)
  {
      //     Type,              name, amount
      allocv(Lists::List<Node>, root, 1); // custom malloc that increases some x value where x for checking memory leaks after code has exit
      *root = Lists::List<Node>();
      data = root;

      // tokens.start = List::Node<Token>* start of list
      while (tokens.start)
        // pop_first (pops first element then free tokens.start)
        // tokens.start = tokens.start.next
        // push_back (malloc)
        root->push_back(Node(this, tokens.pop_first()));
    }
}
c++ memory-management
1个回答
0
投票

感谢@Barmar,我使用 realloc() 找到了答案

#include <stdlib.h>

struct someStruct
{
    int x, y, z;
    float w;
};

struct node
{
    struct someStruct value; // changed positions on memory with-
    struct node *prev, *next; // this
};

struct someStruct* extract(struct node* old)
{
    return (struct someStruct*)realloc(old, sizeof(someStruct));
}
© www.soinside.com 2019 - 2024. All rights reserved.