I have a header file calloc.h, where I defined calloc() function using stdlib's malloc() function. But I am getting multiple definition of 'calloc' error.
calloc.h:
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
void *calloc(size_t num, size_t size)
{
/* num * size unsigned integer wrapping check */
if ((num >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && num > 0 && SIZE_MAX / num < size)
{
return NULL;
}
size_t total_size = num * size;
void *ptr = malloc(total_size);
if (ptr)
{
memset(ptr, 0, total_size);
}
return ptr;
}
Is there any way to resolve this issue?
I tried this:
#define calloc _calloc_
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#undef calloc
But I am getting the following error:
cstdlib:144:11: error: 'calloc' has not been declared in '::'
stdlib.h:59:12: error: 'calloc' has not been declared in 'std'
The link time error you get seems to indicate the module in the C library that defines
calloc()is linked into your program, not because you redefoinecalloc, but because you use at least another symbol defined in the same module. It is possible that bothcallocandmallocare defined in the same module in your C library, which means you cannot redefinecalloc()with a call tomalloc().Also note that you seem to be compiling your C source file as C++.
On your system, you may have to redefine both
malloc(),calloc(),realloc(),free()and possibly other library functions such asstrdup(),aligned_alloc(), so none of the original allocation modules get pulled into your executable. This is a non trivial task.If you want to divert the calls to
calloc()in a program, you can add a command line definition such as-Dcalloc=my_callocso all source files end up calling your function instead of the standard library function.