If there's a reasonable upper bound on the record size, allocate a global read-only variable containing zeros. (Since it's a static-duration object, it's automatically initialized to zero.)
const unsigned char zero_filled_buffer[MAX_RECORD_SIZE]; /*at file scope*/
If the write function is a C fwrite
or POSIX write
or other function, you can (must, for write
) call it in a loop, so the buffer doesn't have to be as big as the biggest record, just as big as the biggest chunk you write at once.
Such a variable will take zero space in your executable file under typical hosted implementations. ADDED: Note that as far as the C standard is concerned, the declaration above is exactly equivalent to const unsigned char zero_filled_buffer[MAX_RECORD_SIZE] = {0};
however some compilers (including gcc) include the zeros in the executable if you explicitly add = {0}
but not if you leave off the initializer.
A smart program loader on a system with virtual memory could take advantage of the virtual memory system to use a single shared read-only zero-filled page of physical RAM for all such objects; I don't know if any do in practice. ADDED: For example, Linux (Debian lenny amd64) doesn't.
An alternative POSIX approach is to mmap
the file and call memset
to zero-fill buffers.