Skip to Content
Course content

46: Dynamic Arrays with new[]

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 using new[].
  • 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.