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.
calloc(1, num_bytes)
num_bytes
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?
calloc
, :
// 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 .
memset
, , mmap(2) VirtualAlloc, , . . . .
mmap(2)
VirtualAlloc
calloc malloc memset , , .
, calloc() , , size_t ( 64KiB).
calloc()
size_t
, calloc() . , , - , , . , .
calloc(), malloc() - , calloc() do.
malloc()
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.
alloc
All this is a very minor optimization (with the possible exception of reuse alloc). Instead, I would focus on the algorithm.