Skip to content

Use a unique_ptr for buffer_ #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 5 additions & 16 deletions src/MemoryBuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,19 @@
#include "MemoryBuffer.h"
#include <Arduino.h>

MemoryBuffer::MemoryBuffer(size_t size) : size_(size), buffer_(nullptr)
MemoryBuffer::MemoryBuffer(size_t size) : size_(size)
{
if (size_ > 0)
{
buffer_ = static_cast<uint8_t *>(malloc(size_));
if (buffer_ == nullptr)
{
buffer_ = std::make_unique<uint8_t[]>(size);
if (buffer_.get() == nullptr)
log_e("Memory allocation failed!");
}
}
}

MemoryBuffer::~MemoryBuffer()
{
if (buffer_ != nullptr)
{
free(buffer_);
buffer_ = nullptr;
}
}

uint8_t *MemoryBuffer::get()
{
return buffer_;
return buffer_.get();
}

size_t MemoryBuffer::size() const
Expand All @@ -57,5 +46,5 @@ size_t MemoryBuffer::size() const

bool MemoryBuffer::isAllocated()
{
return buffer_ != nullptr;
return buffer_.get() != nullptr;
}
12 changes: 3 additions & 9 deletions src/MemoryBuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#define MEMORYBUFFER_H

#include <Arduino.h>
#include <memory>

/**
* @class MemoryBuffer
Expand Down Expand Up @@ -66,13 +67,6 @@ class MemoryBuffer
*/
explicit MemoryBuffer(size_t size);

/**
* @brief Destructor that frees the allocated memory.
*
* The destructor automatically frees the memory allocated for the buffer when the object is destroyed.
*/
~MemoryBuffer();

/**
* @brief Returns a pointer to the allocated memory buffer.
*
Expand All @@ -95,8 +89,8 @@ class MemoryBuffer
bool isAllocated();

private:
size_t size_; // Size of the allocated buffer
uint8_t *buffer_; // Pointer to the allocated buffer
size_t size_;
std::unique_ptr<uint8_t[]> buffer_;
};

#endif // MEMORYBUFFER_H