C/C++ Coding Tips
Allocating dynamic memory
- Function malloc allocates but does not initialize values: use calloc (allocate/initialize) or memset (initialize)
- In C++, new operator calls malloc and then calls the constructor for each created object
- On failure, malloc and new return 0: when new fails, _new_handler is called if set (set by set_new_handler)
Deallocating dynamic memory
- Function free crashes if passed a null pointer
- In C++, delete operator first calls destructor of object(s) and then calls free: delete ignores null pointers
- Use delete [] arrayPtr to deallocate an array
- Zero pointer after deallocating it to prevent redeletion
- Deallocate a pointer before reassigning it