Next: , Previous: , Up: Extension API Description   [Contents][Index]


16.4.4 Memory Allocation Functions and Convenience Macros

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.

void *gawk_malloc(size_t size);

Call gawk-provided api_malloc() to allocate storage that may be passed to gawk.

void *gawk_calloc(size_t nmemb, size_t size);

Call gawk-provided api_calloc() to allocate storage that may be passed to gawk.

void *gawk_realloc(void *ptr, size_t size);

Call gawk-provided api_realloc() to allocate storage that may be passed to gawk.

void gawk_free(void *ptr);

Call gawk-provided api_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.98 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 the API-provided function pointers api_malloc() and api_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:

pointer

The pointer variable to point at the allocated storage.

type

The type of the pointer variable, used to create a cast for the call to api_malloc().

size

The total number of bytes to be allocated.

message

A 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 api_realloc(), instead of api_malloc(). The arguments are the same as for the emalloc() macro.


Footnotes

(98)

This is more common on MS-Windows systems, but can happen on Unix-like systems as well.


Next: , Previous: , Up: Extension API Description   [Contents][Index]