Answer the question
In order to leave comments, you need to log in
When to use malloc() or calloc()?
Reading articles on Habré, I noticed that the malloc () and calloc () functions are often used there.
They are used to allocate memory.
But even with a simple definition of a variable, memory is also allocated for it.
So what is the main difference between these two methods?
Or are these 2 functions a more flexible analog of just declaring a variable? (In the sense that the programmer himself decides the size of the allocated area)
How to understand when which method to use is more correct?
Answer the question
In order to leave comments, you need to log in
A simple variable allocates memory on the stack. The memory on the stack must be of a fixed size and known at the time of compiling the program, otherwise the program simply will not work.
malloc() and calloc() allocate memory on the heap, it can be of any size (no more than there is free memory in the system, of course) and it is not necessary to know its size at the time of compilation. There will be only a pointer on the stack, which has a fixed size.
calloc is used to allocate memory for arrays, it takes 2 arguments, the number of array elements and the size of one element in bytes. malloc takes 1 argument, which is the size of the allocated memory in bytes. Essentially the same thing, but calloc fills the allocated memory with zeros, which removes all the remaining garbage in the allocated memory.
In short, during the execution of a program, there are two areas of memory in which memory can be allocated.
The stack differs in the speed of allocating space for a variable, but is limited in size and lifetime of the variable itself (It is destroyed when it goes out of scope). Consequently, it is not always reasonable to create large, long-lived objects on the stack.
A heap, on the contrary, is a more expensive operation in terms of memory allocation time, but you control the lifetime of variables yourself and there are more places on average. Allocators (malloc, calloc, etc.) just allocate memory on the heap.
malloc
is not subject to any automatic memory deallocation mechanisms. Such memory will remain allocated "forever" until you free it yourself by calling free
. In other words, unlike automatic variables, objects allocated in dynamic memory are not destroyed when the block exits. Simply put, dynamic memory exists primarily so that you can allocate it in a function, but not release it when the function exits. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question