142. Static Object Pool

In high-performance firmware (like network drivers), creating and destroying thousands of packets per second using malloc causes fragmentation and CPU overhead. A Static Object Pool solves this by pre-allocating a fixed array of objects at compile time and managing them manually.

Your task is to implement a MessagePool class.

  1. Define a static array of 3 Message objects.
  2. Define a static array of 3 bool flags (in_use) to track availability.
  3. Implement static Message* allocate():
    • Find the first index i where in_use[i] is false.
    • Set in_use[i] = true.
    • Return a pointer to pool[i].
    • If all are in use, return nullptr.
  4. Implement static void release(Message* m):
    • Calculate the index i based on the pointer address (pointer arithmetic).
    • Set in_use[i] = false.

Program Flow:

  1. Read integer N (number of commands).
  2. Loop N times.
  3. Read string cmd.
  4. If cmd is "ALLOC":
    • Read integer id.
    • Call allocate(). If successful, set msg->id = id and print Allocated Slot <index>. Else print Pool Full.
  5. If cmd is "FREE":
    • Read integer slot_index.
    • Call release() on the address of that specific slot (simulating a pointer passed back from the application). Print Freed Slot <index>.

Input Format:

  • First line: Integer N (1 to 20).
  • Next N lines: String cmd ("ALLOC", "FREE"), followed by values.
  • Input is provided via standard input (stdin).

Output Format:

  • Allocated Slot <index> or Pool Full
  • Freed Slot <index>
  • Each output must be on a new line.

Example: Example 1

Input:

5
ALLOC 100
ALLOC 200
ALLOC 300
ALLOC 400
FREE 1

Output:

Allocated Slot 0
Allocated Slot 1
Allocated Slot 2
Pool Full
Freed Slot 1

Constraints:

  • Pool size is strictly 3.
  • Must use static arrays for storage.
  • Must not use new or malloc.

 

 

 

Loading...

Input

5 ALLOC 100 ALLOC 200 ALLOC 300 ALLOC 400 FREE 1

Expected Output

Allocated Slot 0 Allocated Slot 1 Allocated Slot 2 Pool Full Freed Slot 1