Calloc (): are individual values ​​important for performance?

I am currently writing an embedded C application where performance is critical.

Currently, I allocate a lot of empty memory as follows: calloc(1, num_bytes)- however, I simply calculate num_bytesas the product of the number of elements and the size of each element previously in the code as the code that is used to call malloc.

callocseems unique in that it is the only -alloc family memory allocation function that takes two arguments for size. Is there a good reason for this? Are there any implications for defining different arguments? What was the rationale for choosing this layout argument?

+5
source share
3 answers

, :

// On a 32-bit system, the calloc will almost certainly fail, but the malloc
// will succeed to overflow, likely leading to crashes and/or security holes
// (e.g. if the number of items to allocate came from an untrusted source)
void *a = calloc(64, 67108865);  // 2^32/64 + 1
void *b = malloc(64 * 67108865);  // will allocate 64 bytes on 32-bit systems

calloc malloc memset, calloc .

, , ​​ mmap(2) VirtualAlloc, , . . . .

calloc malloc memset , , .

+3

, calloc() , , size_t ( 64KiB).

, calloc() . , , - , , . , .

calloc(), malloc() - , calloc() do.

+1

C, .

I think optimization callocshould be pretty low as a priority. But try to see if it can be used instead malloc(avoiding zero initialization), avoided allocaltogether by reusing memory and, possibly, allocating memory supplemented by the boundary of a particular platform.

All this is a very minor optimization (with the possible exception of reuse alloc). Instead, I would focus on the algorithm.

0
source

All Articles