Previous: Subexpression Complications, Up: Regular Expressions
When you are finished using a compiled regular expression, you can
free the storage it uses by calling regfree
.
Calling
regfree
frees all the storage that*
compiled points to. This includes various internal fields of theregex_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.
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
orregexec
was working with when it got the error. Alternatively, you can supplyNULL
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 thatregerror
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 callregerror
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; }