libstddjb
libskarnet
skalibs
Software
skarnet.org

The stralloc library interface

The following functions are declared in the skalibs/stralloc.h header, and implemented in the libskarnet.a or libskarnet.so library.

General information

stralloc is the preferred skalibs way of storing objects into heap memory. It focuses on strings of char, which is the generic way to handle any object. For easy structure manipulation, the genalloc series of functions can be used; those functions are mostly macros wrapping calls to their stralloc counterparts.

A stralloc is a structure containing the following fields:

The benefits of using stralloc are as follows:

A stralloc can be declared anywhere: static/global data, stack or heap. (Of course, as a general rule, you should favor the stack whenever possible.) A stralloc should be initialized to STRALLOC_ZERO before its first use.

Functions

int stralloc_catb (stralloc *sa, char const *s, unsigned int len)
Appends the len bytes pointed to by s to the end of the memory zone handled by *sa, automatically allocating more memory if needed. Returns 1 if it succeeds, and 0 if it fails.

void stralloc_free (stralloc *sa)
Frees *sa, i.e. calls alloc_free on sa→s then zeroes the structure. *sa is then reusable. However, it is not good practice to call this function if you're going to reuse *sa soon: it takes time and causes memory fragmentation. Just setting sa→len to 0 allows you to instantly reuse the allocated block of memory.

The above are the most important and fundamental functions of skalibs/stralloc.h. Other functions can be found in this header and their prototypes are self-explaining.