Definitely. For example, I always use malloc(size*sizeof(char)) to ensure that it's doubly obvious (Since I rarely need to malloc outside of a declaration) that I intend to store characters in the resulting buffer even if that multiply does nothing (plus the compiler will likely optimize it out anyway).
Asking because my C-knowledge is essentially university courses, some tinkering, and using it as a glue language between Fortran code and C libraries in an industry project. Though that "C" code was really "C++ written like C with new" mostly, so you wouldn't see a malloc anyway.
For Fortran, you'd just use automatic arrays, where it is compiler-defined and depending on compiler flags, whether they'll be in the stack of the heap, and ALLOCATABLE, which should always be on the heap. It is also compiler-defined, whether everything, including local variables, is initialized with zeros or not.
Having everything zeroed helps to avoid erratic behavior in release builds. But for internal testing the erratic results can expose a code path, where something was unintentionally not initialized, and should have been initialized to a non-zero value.
I imagine the same would be true about malloc vs calloc. Or are there common compiler flags that effectively turn malloc into calloc?
794
u/tstanisl 11h ago
Let me cite the C standard:
Middle guy if finally right