What is the advantage of zeroing out memory (i.e. calloc() over malloc())? Won’t you change the value to something else anyways?
What is the advantage of zeroing out memory (i.e. calloc() over malloc() )? Won’t
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are two camps: one says that initializing variables when they are declared helps find bugs. The people in this camp make sure everything they declare is initialized. They initialize pointers to
NULL,ints to 0, etc. The idea is that everything is determinate, and when they see aNULL-pointer in a debugger, they immediately know it wasn’t set properly. It can also help your program crash during testing because ofNULL-pointer dereferencing rather than mysteriously crashing in production runs.The other camp says that initializing variables at declaration makes things harder to debug, because now a compiler can’t warn you about variables “used without being set”.
Without telling you my personal preference1: if you belong to the first camp, you would want to
calloc()instead ofmalloc(). If you belong to the second camp (which apparently you do) then you prefermalloc()overcalloc().Now there are two exceptions:
calloc()butmalloc()because you are initializing floating-point numbers or pointers, and you know that all bits zero doesn’t necessarily mean0for them. Or, you don’t want the extra overhead.calloc()when you are allocating some data and want it to be all zeroes. For example, if you want to calculate the row-wise sum of annbymdynamically allocatedintdata.1 You can see my answers to many of the questions here on SO to see which camp I belong to :-).