C++

Technical Journal // C++
May '21

Types of Pointers in C/C++

Photo of Hyacinth macaw by Roi Dimor on Unsplash Types of Pointers in C / C++1. Null PointerIt is a pointer pointing to nothing. NULL pointer points to the base address of the segment. -EXAMPLE- c 1int * ptr = (int) * 0; 2float * fptr = (float) * 0; 3double * dptr = (double) * 0; 4char * chptr = (char) * 0; Other ways of initializing NULL pointer c 1int * ptr = NULL; 2char * chptr = '\0'; NULL also means 0 in macro c 1#define NULL 0 2. Dangling PointerA pointer pointing to the memory address of any variable (or object) which has been deleted from memory. When a pointer points to a deleted memory address, the pointer is called as a dangling pointer.

May '21

Avoid Memory Leaks In C++

Instructions Things You’ll Need Proficiency in C++ C++ compiler Debugger and other investigative software tools Part 1Understand the operator basics. The C++ operator new allocates heap memory. The delete operator frees heap memory. For every new, you should use a delete so that you free the same memory you allocated: cpp 1char* str = new char [30]; // Allocate 30 bytes to house a string. 2delete [] str; // Clear those 30 bytes and make str point nowhere. Part 2Reallocate memory only if you’ve deleted. In the code below, str acquires a new address with the second allocation. The first address is lost irretrievably, and so are the 30 bytes that it pointed to. Now they’re impossible to free, and you have a memory leak: