how-to-c-response
how-to-c-response copied to clipboard
Initialize to zero
The problem with always initializing everything to zero is that unitialized memory checkers can't help you. Tools like valgrind can warn you if you use a variable before setting it (perhaps a piece of structure needs a value other than zero?) but this warning is silenced if the memory was created with calloc.
And depending on system, malloc() might not physically take up any memory until you use the memory in question; then depending on system only allocate as much physical memory as you actually use of your allocation.
Again depending on system and functions used, zero initializing the memory (in my experience usually done on the whole requested allocation) might allocate physical memory for it all.
It's not always you know exactly how much memory you need for something so allocations like malloc(max_allowed_size_for_something) are commonly seen. If that memory were to be zero initialized, max_allowed_size_for_something worth of physical memory might be allocated instead of the actual needed size.
As a concurrent concern, if you're porting from Solaris to other systems and the code was written against Sun's toolchain, you'll likely need to change a number of things because their malloc() behaves as calloc() with regard to the state of the allocation. (That was some fun memory corruption to debug.) It's entirely possible that other platforms do this too.
Another issue with struct padding is that (AFAIK) if you copy a padded structure it's not guaranteed that your carefully zero-filled padding bytes will get transferred into the copy.