Why malloc+memset is slower than calloc?

It’s known that calloc is different than malloc in that it initializes the memory allocated. With calloc, the memory is set to zero. With malloc, the memory is not cleared. So in everyday work, I regard calloc as malloc+memset. Incidentally, for fun, I wrote the following code for a benchmark. The result is confusing. Code … Read more

How do malloc() and free() work?

I want to know how malloc and free work. int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,”abcdabcd”); // **deliberately storing 8bytes** cout << p; free(p); // Obvious Crash, but I need how it works and why crash. cout << p; return 0; } I would be really grateful if the answer … Read more

Why is the use of alloca() not considered good practice?

alloca() allocates memory on the stack rather than on the heap, as in the case of malloc(). So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up dynamically allocated memory. Freeing of memory allocated through malloc() is a major headache and if somehow missed leads … Read more

Difference between malloc and calloc?

What is the difference between doing: ptr = malloc (MAXELEMS * sizeof(char *)); or: ptr = calloc (MAXELEMS, sizeof(char*)); When is it a good idea to use calloc over malloc or vice versa? 14 s 14 calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized. For large allocations, most calloc implementations under … Read more

Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this: int *sieve = malloc(sizeof(*sieve) * length); rather than: int *sieve = (int *) malloc(sizeof(*sieve) * length); Why would this be the case? 2 29 TL;DR int *sieve = (int *) malloc(sizeof(int) * length); … Read more

Do I cast the result of malloc?

TL;DR int *sieve = (int *) malloc(sizeof(int) * length); Has two problems in result of malloc. The cast and that you’re using the type instead of variable as argument for sizeof. Instead, do like this: int *sieve = malloc(sizeof *sieve * length); Long version No; you don’t cast the result, since: It is unnecessary, as void * is automatically … Read more