C++
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C++
-
Section 4: Memory Management
-
Section 5: Templates and Generic Programming
-
Section 6: The Standard Template Library
-
Section 7: Modern C++ Features
-
Section 8: Error Handling
-
Section 9: Multithreading
-
Section 10: Operator Overloading and Type Conversion
-
Section 11: Advanced Topics
-
Section 12: Tooling and Build Systems
-
Section 13: Design Patterns in C++
-
Section 14: Interfacing with C and Systems Programming
-
Section 15: Networking and IPC Basics
-
Section 16: Graphics and Game Programming Basics
-
Section 17: The Boost Libraries
-
Section 18: Data Structures and Algorithms in C++
-
Section 19: Practical Projects
-
Section 20: More Concurrency Patterns
-
Section 21: More OOP and Design Practice
-
Section 22: File I/O and Streams
-
Section 23: More Standard Library
-
Section 24: Practice Exercises
-
Section 25: Interview and Algorithm Practice
-
Section 26: Compiler and Language Internals
-
Section 27: GUI and Application Frameworks Overview
-
Section 28: Testing and Quality Practices
-
Section 29: Numerics Library
-
Section 30: Concepts Library (C++20)
-
Section 31: Ranges Library (C++20) In Depth
-
Section 32: More Utility Library
46: Dynamic Arrays with new[]
I was tinkering with a small high-score tracker for a game yesterday, and I ran into a problem that every C++ developer hits early on. I knew I needed an array to hold the scores, but I had no idea how many players would actually join the session. Maybe two, maybe two hundred.
The "Variable Size" Headache
My first instinct was to do something that looks perfectly logical. I tried to let the user tell me the size, and then just declare the array right there. It looked like this:
int playerCount;
std::cin >> playerCount;
int scores[playerCount]; // This looks right, doesn't it?
Here's the thing: if you're using certain compilers (like GCC), this might actually compile and run. They call these Variable Length Arrays (VLAs). But they aren't actually part of the official C++ standard. More importantly, these arrays live on the stack. The stack is fast, but it's small. If a user enters "1,000,000" for the player count, your program isn't going to gracefully tell them it's too much—it's just going to crash with a stack overflow.
Asking the OS for Space
To fix this, I need to move the data off the stack and onto the heap. The heap is a massive pool of memory that we can request chunks from at runtime. In C++, we do this using the new keyword. Since I need an array, not just a single integer, I use the square bracket version: new[].
Let's see what happens when I rewrite that block:
int playerCount;
std::cin >> playerCount;
// I'm telling the OS: "Give me enough room for X integers on the heap"
int* scores = new int[playerCount];
// Now I can use it just like a normal array
for (int i = 0; i < playerCount; ++i) {
scores[i] = 0;
}
Notice that scores is no longer just an array; it's a pointer. It holds the memory address of the very first element of that block on the heap. This is a powerful shift. The size of the array is now determined while the program is running, not while it's compiling.
Cleaning up the Mess
I ran my program a few times, and I noticed something concerning in my system monitor: the memory usage was climbing every time I ran the loop, even though I thought I was done with the array. I realized I was committing the cardinal sin of C++: the memory leak.
When you use new, the OS marks that memory as "taken" until you explicitly tell it that you're finished. Unlike local variables on the stack, heap memory doesn't vanish when the function ends. It stays there, stubbornly occupying space, until the program terminates or you delete it.
Since I allocated this as an array (using new[]), I have to use the array version of delete:
delete[] scores;
I'll be honest: I've spent hours debugging crashes because I used delete scores; instead of delete[] scores;. If you forget the brackets, the compiler might only delete the first element of the array, leaving the rest of the memory hanging in limbo. It's an undefined behavior nightmare. Always pair new[] with delete[]. No exceptions.
Putting it all together
So, the workflow I settled on for my score tracker looks like this: request the size, allocate with new[], do the work, and immediately delete[] once the data is no longer needed. It's a manual process, and while modern C++ has tools like std::vector to automate this, understanding this manual "handshake" with the memory is how you actually learn what's happening under the hood of your computer.
📋 Practical Task
Exercise: Dynamic Temperature Log Processor
You are building a tool to analyze temperature readings. Since the number of readings varies by day, you cannot use a fixed-size array.
Write a program that performs the following steps:
- Ask the user how many temperature readings they have recorded today.
- Dynamically allocate an array of
doubles to hold that exact number of readings usingnew[]. - Use a loop to let the user input each temperature value.
- Calculate and print the average temperature of the set.
- Properly deallocate the memory using
delete[]to ensure there are no memory leaks.
There are no comments for now.