malloc() vs calloc()

What is the difference between doing:ptr = (char **) malloc (n * sizeof(char *));or:ptr = (char **) calloc (n, sizeof(char*));When is it a good idea to use callocovermalloc or vice versa?Answer1.calloc()zero-initializes the buffer, whilemalloc()leaves the memory uninitialized.Zeroing out the memory may take a little time, so you probably want to usemalloc()if that performance is an issue. If initializing the memory is more important, use calloc(). For example,calloc()might save you a call tomemset().2.Usemalloc()if you are going to set everything that you use in the allocated space. Usecalloc()if you’re going to leave parts of the data uninitialized – and it would be beneficial to have the unset parts zeroed.3.One often-overlooked advantage ofcalloc()is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);vs.size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);The former could result in a tiny allocation and subsequent bufferoverflows, ifcountis greater thanSIZE_MAX/sizeof *bar. The latter will automatically fail in this case since an object that large cannot be created.

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *