C++20 Recipes by J. Burton Browning & Bruce Sutherland

C++20 Recipes by J. Burton Browning & Bruce Sutherland

Author:J. Burton Browning & Bruce Sutherland
Language: eng
Format: epub
ISBN: 9781484257135
Publisher: Apress


using namespace std;

int main(int argc, char* argv[])

{

int* pInt{ new int };

*pInt = 100;

cout << hex << "The address at pInt is " << pInt << endl;

cout << dec << "The value at pInt is " << *pInt << endl;

delete pInt;

pInt = nullptr;

return 0;

}

Listing 10-6Using new and delete

This code uses the new operator to allocate enough memory to store a single int variable. A pointer is returned from new and stored in the variable pInt. The memory returned is uninitialized, and it’s generally a good idea to initialize this memory at the point of creation. You can see this in main, where the pointer dereference operator is used to initialize the memory pointed to by pInt to 100.

Once you have allocated memory from the heap, it’s your responsibility to ensure that it’s returned correctly to the operating system. Failing to do so results in a memory leak. Memory leaks can cause problems for users and often result in poor computer performance, memory fragmentation, and, in severe cases, computer crashes due to insufficient memory.

You return heap memory to the operating system using the delete operator . This operator tells the system that you no longer need all the memory that was returned from the initial call to new. Your program should no longer attempt to use the memory returned by new after the call to delete has been made. Doing so causes undefined behavior that more often than not results in a program crash. Crashes caused by access to freed memory are usually very difficult to find, because they manifest themselves in places that you can’t link to the offending code in any way. You can ensure that your program doesn’t access deleted memory by setting any pointers to the memory to nullptr.

The output from Listing 10-6 is shown in Figure 10-5.

Figure 10-5The output showing the address of and value stored in dynamically allocated memory from Listing 10-6



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.