Next: Constructor Functions, Previous: General Data Types, Up: Extension API Description [Contents][Index]
The API provides a number of memory allocation functions for
allocating memory that can be passed to gawk, as well as a number of
convenience macros.
This subsection presents them all as function prototypes, in
the way that extension code would use them:
void *gawk_malloc(size_t size);Call the correct version of malloc() to allocate storage that may
be passed to gawk.
void *gawk_calloc(size_t nmemb, size_t size);Call the correct version of calloc() to allocate storage that may
be passed to gawk.
void *gawk_realloc(void *ptr, size_t size);Call the correct version of realloc() to allocate storage that may
be passed to gawk.
void gawk_free(void *ptr);Call the correct version of free() to release storage that was
allocated with gawk_malloc(), gawk_calloc(), or gawk_realloc().
The API has to provide these functions because it is possible
for an extension to be compiled and linked against a different
version of the C library than was used for the gawk
executable.100 If gawk were
to use its version of free() when the memory came from an
unrelated version of malloc(), unexpected behavior would
likely result.
Two convenience macros may be used for allocating storage
from gawk_malloc() and
gawk_realloc(). If the allocation fails, they cause gawk
to exit with a fatal error message. They should be used as if they were
procedure calls that do not return a value:
#define emalloc(pointer, type, size, message) …The arguments to this macro are as follows:
pointerThe pointer variable to point at the allocated storage.
typeThe type of the pointer variable. This is used to create a cast for
the call to gawk_malloc().
sizeThe total number of bytes to be allocated.
messageA message to be prefixed to the fatal error message. Typically this is the name of the function using the macro.
For example, you might allocate a string value like so:
awk_value_t result; char *message; const char greet[] = "Don't Panic!"; emalloc(message, char *, sizeof(greet), "myfunc"); strcpy(message, greet); make_malloced_string(message, strlen(message), & result);
#define erealloc(pointer, type, size, message) …This is like emalloc(), but it calls gawk_realloc()
instead of gawk_malloc().
The arguments are the same as for the emalloc() macro.
This is more common on MS-Windows systems, but it can happen on Unix-like systems as well.
Next: Constructor Functions, Previous: General Data Types, Up: Extension API Description [Contents][Index]