71. DataBuffer Fixed Buffer Init

#include <iostream>
using namespace std;

class DataBuffer {
private:
    int size;              // Effective buffer size (1–20)
    int buffer[20];        // Fixed-size internal storage
    int writeIndex;        // Next write position

public:
    // Constructor
    DataBuffer(int s) {
        // Clamp size between 1 and 20
        if (s < 1)
            size = 1;
        else if (s > 20)
            size = 20;
        else
            size = s;

        // Initialize all 20 elements to zero
        for (int i = 0; i < 20; i++) {
            buffer[i] = 0;
        }

        writeIndex = 0;
    }

    // Push value into buffer if space is available
    void push(int v) {
        if (writeIndex < size) {
            buffer[writeIndex] = v;
            writeIndex++;
        }
        // Ignore writes when buffer is full
    }

    // Print stored values
    void print() {
        for (int i = 0; i < writeIndex; i++) {
            cout << buffer[i];
            if (i + 1 < writeIndex) {
                cout << " ";
            }
        }
    }
};

int main() {
    int s, n;
    cin >> s >> n;

    DataBuffer buf(s);

    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        buf.push(x);
    }

    buf.print();
    return 0;
}

Explanation & Logic Summary:

  • Constructor clamps the effective buffer size to a safe range
  • Entire fixed buffer is zero-initialized to avoid undefined memory
  • writeIndex tracks valid stored elements
  • Overflow writes are ignored without side effects
  • This models predictable and safe embedded buffer behavior

Firmware Relevance & Real-World Context:

  • Fixed-size buffers are common in firmware (DMA, FIFOs, message queues)
  • Deterministic initialization is critical after reset
  • Size clamping prevents invalid runtime configurations
  • Overflow protection avoids memory corruption in constrained systems
Loading...

Input

5 7 1 2 3 4 5 6 7

Expected Output

1 2 3 4 5