Lesson 20 of 24

Pointers, new/delete and Smart Pointers

11 min 35 XP

new allocates heap memory and delete frees it; forget the delete and you leak memory. Modern C++ uses unique_ptr and shared_ptr, which free memory automatically.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Pair new[] with delete[] and new with delete; mixing them is undefined behaviour. Smart pointers avoid these mistakes entirely.

Challenge

+35 XP

Singly linked list: read n and n numbers, insert each at the head of the list, then print the list from the head. (Use unique_ptr or new for the nodes.) Input: 4 1 2 3 4 Output: 4 3 2 1

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.