I was trying to redirect std::cout to use #include "stream_buffer.h" but facing issues

#include <iostream>
#include <streambuf>
#include <stdexcept>
#include "FreeRTOS.h"
#include "stream_buffer.h"

class FreeRTOSStreamBuffer : public std::streambuf {
    FreeRTOSStreamBuffer(size_t bufferSize) {
        // Create the FreeRTOS stream buffer
        xStreamBuffer = xStreamBufferCreate(bufferSize, 1);
        if (xStreamBuffer == nullptr) {
            throw std::runtime_error("Failed to create FreeRTOS stream buffer");

    ~FreeRTOSStreamBuffer() {

    virtual int_type overflow(int_type c) override {
        if (c != EOF) {
            char z = c;
            if (xStreamBufferSend(xStreamBuffer, &z, 1, portMAX_DELAY) != 1) {
                return EOF;
        return c;

    virtual std::streamsize xsputn(const char* s, std::streamsize n) override {
        return xStreamBufferSend(xStreamBuffer, s, n, portMAX_DELAY);

    StreamBufferHandle_t xStreamBuffer;

int main() {
    // Create an instance of FreeRTOSStreamBuffer
    FreeRTOSStreamBuffer myStreamBuffer(1024); // Size of the stream buffer

    // Set the custom stream buffer for std::cout

    // Now you can use std::cout as usual
    std::cout << "Hello, FreeRTOS Stream Buffer!" << std::endl;

    return 0;

my class gives me an error when I try to inherent public std::streambuf. it goes into trap
I have enabled
#define configUSE_STREAM_BUFFERS 1
#define configUSE_NEWLIB_REENTRANT 1

It would be helpful to know what “error” you get.

One thing I do see is that you have not done anything to ensure the requirement that only one task (at a time) is trying to send with the buffer. If two tasks send to the StreamBuffer at the same time, your code can violate that requirement.

To add on to @richard-damon 's comment, I would suggest using either a critical section or mutex to ensure only a single task is able to write to the stream buffer at any given time.