CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
Scratch Buffers

Data Structures

struct  ScratchPerThreadInfo
 Per-thread scratch buffer state. More...
 

Macros

#define SCRATCH_NBUFFERS   32
 Number of rotating buffers per thread (must be power of 2)
 
#define SCRATCH_MIN_BUFFER_SIZE   64
 Minimum size for scratch buffer allocations.
 
#define SCRATCH_MAX_REASONABLE_BUFFER_SIZE   1024
 Maximum size before buffer is considered unreasonably large.
 

Typedefs

typedef struct ScratchPerThreadInfo ScratchPerThreadInfo
 Per-thread scratch buffer state.
 

Functions

void * scratchGet (size_t sz)
 

Detailed Description

Scratch buffers provide thread-local temporary storage through a rotating buffer pool. Each thread maintains its own set of buffers that are automatically allocated on demand and reused across function calls within the same thread.

Critical Usage Rules:

  1. Do NOT save pointers to scratch buffers in any persistent structure
  2. Do NOT share pointers across thread boundaries
  3. Do NOT use in recursive functions - buffers rotate and will be overwritten
  4. Be aware of function calls - any function using scratch buffers may invalidate buffers the caller was using
  5. Keep sizes reasonable - large allocations defeat the purpose
  6. Not for performance-critical paths - allocation has overhead

Buffer Pool Behavior:

Example:

// Get temporary buffer for string formatting
char *temp = scratchGet(256);
sprintf(temp, "Value: %d", value);
processString(temp); // Use immediately
// Don't save 'temp' - it may be overwritten by next scratchGet call
void * scratchGet(size_t sz)

Function Documentation

◆ scratchGet()

void * scratchGet ( size_t  sz)

Allocates a temporary scratch buffer from the thread-local rotating pool.

Returns the next buffer in the rotation, resizing if necessary. The buffer is NOT zero-filled and may contain stale data from previous uses. Buffers rotate after SCRATCH_NBUFFERS allocations, so earlier buffers may be overwritten.

Warning: Do not assume the returned pointer remains valid after calling other functions that may use scratch buffers, or after SCRATCH_NBUFFERS additional scratchGet calls.

Parameters
szRequired buffer size in bytes (minimum SCRATCH_MIN_BUFFER_SIZE)
Returns
Pointer to scratch buffer (never NULL)