恶意和可用内存泄漏

malloc and free memory leakage

本文关键字:内存 泄漏 恶意      更新时间:2023-10-16

im 试图创建一个具有 malloc 的类。

  • 该类具有内部结构。
  • 用户将有指向结构的指针,但他可能不知道结构,甚至不关心它。

  • 他必须保存指针,某些函数将需要该结构的地址。

因此,在库的标题中,我执行以下操作:

#define EELS_MAX_SLOTS 5
class EELS
{
typedef struct{
   //struct difinition ...
}ee_slot_t;
public:
    EELS();
    uint8_t CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length);
    ~EELS();
protected:
private:
    void* _slot_arr[EELS_MAX_SLOTS];
    uint8_t _slot_counter;
}; 

以及执行文件中的代码:

// default constructor
EELS::EELS()
{
    _slot_counter =0;
} //EELS
uint8_t EELS::CreateSlot(uint16_t begin_addr, uint16_t length, uint8_t data_length){
    if (_slot_counter > EELS_MAX_SLOTS)
        return NULL;
    ee_slot_t* slot_p;
    slot_p = malloc(sizeof(ee_slot_t))
    if (!slot_p)
        return NULL;
    slot_p->begining = begin_addr;
    slot_p->length = length;
    slot_p->counter  = 0; // TODO...init...
    slot_p->position = 0; // TODO...init...
    _slot_arr[_slot_counter] = (void*)slot_p;
    _slot_counter++;
    return _slot_counter;
}
// default destructor
EELS::~EELS()
{
    for (int i=0; i<_slot_counter; i++)
    {
        free((ee_slot_t*)_slot_arr[i]);
    }
}

如您所见,IM 返回指针数组的索引.. 所以在这种情况下 (1-6(,我将真实地址保存在该指针数组中。

但从你所看到的。 这安全吗? 自由方法和 malloc.. 有一些错误或内存泄漏?

为什么不是矢量?

因为它用于嵌入式系统和当前 IDE/工具链 IM 使用的不支持 std:vectors。

当_slot_counter == EELS_MAX_SLOTS时会发生什么。所以我认为你应该改变 if 语句

if (_slot_counter > EELS_MAX_SLOTS)
    return NULL;

if (_slot_counter >= EELS_MAX_SLOTS)
    return 0; // return type is uint8_t, not a pointer