I would like to convert malloc() to calloc(). I am confused about using calloc() in this example because it takes 2 arguments while malloc() only one. So it's correct with mine:
(byteBuffer)calloc(sizeof(byteBufferStruct), len + 1));
The example:
typedef struct byte_buf {
size_t len;
uint8_t *bytes;
} byteBufferStruct, *byteBuffer;
byteBuffer mallocByteBuffer(size_t len)
{
byteBuffer retval;
if((retval = (byteBuffer) malloc(sizeof(byteBufferStruct) + len + 1)) == NULL) return NULL;
retval->len = len;
retval->bytes = (uint8_t *) (retval + 1) ; /* just past the byteBuffer in malloc'ed space */
return retval;
}
First: Both
malloc()
andcalloc()
returnvoid *
, which in C means you should not cast the return value.Comparing the signatures of the functions, we have:
void * malloc(size_t size);
void * calloc(size_t nmemb, size_t size);
Basically, the argument to
malloc()
is the product of the arguments tocalloc()
.You can convert by just setting one of them to 1:
Since the
nmemb
(number of members) tocalloc()
doesn't affect the actual structure of the memory in any way, this is safe.Now we can use this to implement your allocation function (for clarity):
Note that
sizeof
is not a function. Also note the glaring asymmetry of asterisks that you get when youtypedef
away the asterisk. I don't recommend ever doing that.