Answer the question
In order to leave comments, you need to log in
What is the difference between malloc() and calloc() and free() and dellete()?
Let's allocate memory
int *x = (int*) malloc(10);
int *y = (int*) calloc(10, sizeof(int));
int *y = (int*) calloc(3, sizeof(int));
int *x = (int*) malloc(12);
Answer the question
In order to leave comments, you need to log in
The only difference is that calloc zeros out the allocated memory before returning the pointer, while malloc does not. Inside calloc, it probably calls malloc to allocate memory, and then memset to zero. So calloc is just an add-on to malloc for convenience. Here is a schematic implementation of calloc:
void * calloc (size_t num, size_t size)
{
void * mem = malloc(num * size);
memset(mem, 0, num * size);
return mem;
}
int a = 0x33323130;
char * c = (char*)&a;
printf("%c %c %c %c\n", c[0], c[1], c[2], c[3]);
The difference is in filling with zeros (initialization). About the definition of what is where, I did not understand. C does not track this at all. Both functions give you absolutely identical pointers, what to do with them is up to you.
About different signatures - they say that calloc, when multiplying arguments, monitors integer overflow and returns NULL in the case when it happened. With malloc, you have to do it yourself.
if you are programming in C++, then it is better not to allocate memory using malloc/calloc, but to create arrays of objects or base types using new . and for direct work with memory it is necessary to have very weighty substantiation.
there is no such dellete() there is a delete
operator that releases what is allocated new
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question