Skip to content

Instantly share code, notes, and snippets.

@assyrianic
Last active January 14, 2024 18:13
Show Gist options
  • Save assyrianic/3f7bc754704070b3aeb897a78ae9c295 to your computer and use it in GitHub Desktop.
Save assyrianic/3f7bc754704070b3aeb897a78ae9c295 to your computer and use it in GitHub Desktop.
realloc that works like calloc.
/**
recalloc
Copyright 2020 Kevin Yonan aka Nergal
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef RECALLOC_INCLUDED
# define RECALLOC_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
/**
* 'recalloc'
* because 'realloc' doesn't zero-memory like 'calloc' can.
* zeroing is only if the new size is larger.
* decreasing simply uses 'realloc' since it won't introduce garbage values.
*/
#ifdef __cplusplus
static void *recalloc(void *const arr, const size_t new_size, const size_t element_size, const size_t old_size)
{
if( arr==nullptr || old_size==0 ) {
return calloc(new_size, element_size);
}
uint8_t *const new_block = reinterpret_cast< uint8_t* >(realloc(arr, new_size * element_size));
if( new_block==nullptr ) {
return nullptr;
}
if( old_size < new_size ) {
memset(&new_block[old_size * element_size], 0, (new_size - old_size) * element_size);
}
return new_block;
}
#else
static void *recalloc(void *const arr, const size_t new_size, const size_t element_size, const size_t old_size)
{
if( arr==NULL || old_size==0 ) {
return calloc(new_size, element_size);
}
uint8_t *const restrict new_block = realloc(arr, new_size * element_size);
if( new_block==NULL ) {
return NULL;
}
if( old_size < new_size ) {
memset(&new_block[old_size * element_size], 0, (new_size - old_size) * element_size);
}
return new_block;
}
#endif
#ifdef __cplusplus
}
#endif
#endif /** RECALLOC_INCLUDED */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment