T_REALLOC convenience macro to reallocate memory
ptr
pointer variable to assign reallocated memory to
size
number of bytes to reallocate
type
data type to cast reallocated memory to
None
None
T_REALLOC uses TutRealloc to reallocate memory, assigns the new memory to the pointer variable ptr
, and checks for errors (realloc returning NULL
). Because TutRealloc returns a T_PTR pointer, type
is used to cast the new memory to the appropriate type, to make the intention of the code clearer.
T_REALLOC can be used in most C contexts. T_REALLOC cannot be used in an expression.
T_REALLOC has the additional feature of being able to handle a NULL
pointer. T_REALLOC checks if ptr
is NULL
, and if so, uses TutMalloc instead of TutRealloc. (Very few realloc implementations can handle NULL
.) This is very useful for data structures that dynamically resize.
type
is used to build a cast and should not have parentheses around it.
T_CALLOC, T_FREE, T_MALLOC, T_STRDUP
This example uses an abstract data type that implements strings that do their own memory management to do a safe strcpy without T_REALLOC.
struct safe_string { T_INT4 size; T_STR buf; }; T_STR safe_strcpy(string_ptr, string) struct safe_string *string_ptr; T_STR string; { T_INT4 string_size; T_ASSERT(string_ptr != NULL); T_ASSERT(string != NULL); string_size = strlen(string) + 1;/* add one for NUL */
if (string_size > string_ptr->size) { if (string_ptr->size == 0) { string_ptr->size += string_size; string_pt r->buf = malloc(string_ptr->size); } else { string_ptr->size += string_size; string_ptr->buf = realloc(string_ptr->buf, string_ptr->size); } if (string_ptr->buf == NULL) { TutWarning("safe_strcpy: alloc failed"); } }strcpy(string_ptr->buf, string); return string_ptr->buf; }
/* safe_strcpy */
With T_REALLOC, the code for safe_strcpy
is:
T_STR safe_strcpy(string_ptr, string) struct safe_string *string_ptr; T_STR string; { T_INT4 string_size; T_ASSERT(string_ptr != NULL); T_ASSERT(string != NULL); string_size = strlen(string) + 1;/* add one for NUL */
if (string_size > string_ptr->size) { string_ptr->size += string_size; T_REALLOC(string_ptr->buf, string_ptr->size, T_STR); } strcpy(string_ptr->buf, string); return string_ptr->buf;/* safe_strcpy */
TIBCO SmartSockets™ Utilities Software Release 6.8, July 2006 Copyright © TIBCO Software Inc. All rights reserved www.tibco.com |