POSIX Regexp Matching Cleanup
-----------------------------
When you are finished using a compiled regular expression, you can
free the storage it uses by calling `regfree'.
- Function: void regfree (regex_t *COMPILED)
Calling `regfree' frees all the storage that `*COMPILED' points
to. This includes various internal fields of the `regex_t'
structure that aren't documented in this manual.
`regfree' does not free the object `*COMPILED' itself.
You should always free the space in a `regex_t' structure with
`regfree' before using the structure to compile another regular
expression.
When `regcomp' or `regexec' reports an error, you can use the
function `regerror' to turn it into an error message string.
- Function: size_t regerror (int ERRCODE, regex_t *COMPILED, char
*BUFFER, size_t LENGTH)
This function produces an error message string for the error code
ERRCODE, and stores the string in LENGTH bytes of memory starting
at BUFFER. For the COMPILED argument, supply the same compiled
regular expression structure that `regcomp' or `regexec' was
working with when it got the error. Alternatively, you can supply
`NULL' for COMPILED; you will still get a meaningful error
message, but it might not be as detailed.
If the error message can't fit in LENGTH bytes (including a
terminating null character), then `regerror' truncates it. The
string that `regerror' stores is always null-terminated even if it
has been truncated.
The return value of `regerror' is the minimum length needed to
store the entire error message. If this is less than LENGTH, then
the error message was not truncated, and you can use it.
Otherwise, you should call `regerror' again with a larger buffer.
Here is a function which uses `regerror', but always dynamically
allocates a buffer for the error message:
char *get_regerror (int errcode, regex_t *compiled)
{
size_t length = regerror (errcode, compiled, NULL, 0);
char *buffer = xmalloc (length);
(void) regerror (errcode, compiled, buffer, length);
return buffer;
}