malloc和释放内存泄漏

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

我尝试创建具有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的..有一些错误或者内存泄露?

why not vector?

因为其用于嵌入式系统和使用犯规支持STD当前IDE /工具链IM:载体。

c++ memory-leaks malloc heap-memory
1个回答
0
投票

时会发生什么_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
© www.soinside.com 2019 - 2024. All rights reserved.