0

malloc and calloc has these signatures:

void* malloc( size_t size );
void* calloc( size_t num, size_t size );

They do basically the same thing. Both allocates a chunk of memory of the specified size and returns a pointer to that chunk. The difference is that calloc initializes the whole memory to zeros. Actually, calloc could be implemented kind of like this:

void* calloc( size_t num, size_t size ) {
    void * ptr = malloc(num*size);
    if(!ptr) return NULL;
    return memset(ptr,0,num*size);
}

(I know that there are reasons to not implement it like this, but that's not the topic.)

Since they are so similar, what is the reason for their different signatures? When you call malloc you specify the number of bytes you want and when you're calling calloc you specify a block size and the number of blocks. I dont prefer one over the other, but it bothers me that they are different.

Imagine that you have written a piece of code with some mallocs, and then you realize that all of these allocations need to be zeroed. If they had the same signature it would mean that you only have to change the "m" to a "c".

Was there ever a reason for this design choice, or was it just a coincidence?

2

The C that was standardized had experienced one and a half decades of organic growth. Not everything has to make perfect sense. Indeed, many standardized functions do not make much sense, such as the inherently unsafe gets() function.

The allocations of calloc(n, sizeof(T)) and malloc(n * sizeof(T)) may allocate different amounts of memory depending on alignment restrictions of the system. This is not an issue on the x86 architecture, but may apply on other architectures.

  • And which might allocate more? Also, why? – Deduplicator Nov 22 '18 at 20:37
1

If size_t is 32 bits, and pointers are 64 but, then they are not equivalent at all if size * nitems doesn’t fit in 32 bits.

  • 2
    I'm not sure whether this is genius language-lawyering or false. The largest size of an object is size_t. Your observation applies iff the memory allocated by malloc() is not an object (but just a memory region that may hold objects). The size of pointers is not immediately relevant as pointers may be much larger than total addressable memory (e.g. some architectures use weird function pointers, so normal pointers are made larger so that all pointers have the same size in C). – amon Nov 22 '18 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.