Skip to content

Commit

Permalink
Add toit_calloc and toit_realloc. (#2312)
Browse files Browse the repository at this point in the history
  • Loading branch information
floitsch committed May 16, 2024
1 parent 75227b7 commit bd78e87
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions include/toit/toit.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,28 @@ toit_err_t toit_gc();
*/
void* toit_malloc(size_t size);

/**
* @brief A wrapper around `calloc` that calls `toit_gc` if `calloc` fails.
*
* If `calloc` fails, this function calls `toit_gc` and then retries the allocation.
*
* @param nmemb The number of elements to allocate.
* @param size The size of each element.
* @return void* A pointer to the allocated memory, or `NULL` if the allocation failed.
*/
void* toit_calloc(size_t nmemb, size_t size);

/**
* @brief A wrapper around `realloc` that calls `toit_gc` if `realloc` fails.
*
* If `realloc` fails, this function calls `toit_gc` and then retries the allocation.
*
* @param ptr The pointer to the memory to reallocate.
* @param size The size of the memory to allocate.
* @return void* A pointer to the allocated memory, or `NULL` if the allocation failed.
*/
void* toit_realloc(void* ptr, size_t size);

#ifdef __cplusplus
}
#endif
14 changes: 14 additions & 0 deletions src/messaging.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1160,4 +1160,18 @@ void* toit_malloc(size_t size) {
return malloc(size);
}

void* toit_calloc(size_t nmemb, size_t size) {
void* ptr = calloc(nmemb, size);
if (ptr != NULL) return ptr;
toit_gc();
return calloc(nmemb, size);
}

void* toit_realloc(void* ptr, size_t size) {
void* new_ptr = realloc(ptr, size);
if (new_ptr != NULL) return new_ptr;
toit_gc();
return realloc(ptr, size);
}

} // Extern C.

0 comments on commit bd78e87

Please sign in to comment.