c++vectormemory-managementstack-overflowsmart-pointers

Why is my vector<uint8_t>[4096] being treated like a pointer and causing a stack overflow?


I'm trying to create a simple Memory class in C++ which simulates 4096 bytes of memory using a vector<uint8_t> array. I wrote an addToMemory function that copies the contents of a vector<uint8_t> into this simulated memory and a print function to print the memory contents. However, when I run the code, I get a stack overflow, and debugging shows that addToMemory uses 131104 bytes of stack, which seems way too much. Also, workingMemory is being treated like a pointer, even though I never declared it as one.

For context, I'm more familiar with higher-level languages like Java, Python, and JavaScript. This is my first time working on a project in C++, so I may be misunderstanding how memory is best managed here.

Here's a minimal example of my code:

main.cpp

#include <iostream>
#include <vector>
#include "Memory.h"
using namespace std;

int main()
{
    vector<uint8_t> gameData = { 1, 2, 3 };
    
    Memory RAM;
    RAM.addToMemory(gameData);
    RAM.print();

    return 0;
}

Memory.h

#pragma once
#include <vector>
using namespace std;

class Memory {
private:
    vector<uint8_t> workingMemory[4096];  
public:
    void addToMemory(vector<uint8_t>& gameData);
    void print();
};

Memory.cpp

#include "Memory.h"
#include <iostream>
using namespace std;

void Memory::addToMemory(vector<uint8_t>& gameData) {
    for (uint8_t i = 0; i < gameData.size(); i++) {
        workingMemory[i] = gameData[i];
    }
}

void Memory::print() {
    cout << "Printing Contents of Working Memory\n";
    for (uint8_t i = 0; i < 4096; i++) {
         cout << workingMemory[i] << "\n";
    }
    cout << "End of Contents of Working Memory\n";
}

What I expected:

That workingMemory would act like a fixed block of memory (size 4096 bytes) that I can store byte values in.

What I'm seeing instead:

Question:


Solution

  • debugging shows that addToMemory uses 131104 bytes of stack, which seems way too much

    A vector takes up 32 bytes on the stack, and you have 4096 of them, for a total of 131,072 bytes.

    Is vector<uint8_t> workingMemory[4096] a bad idea for simulating RAM?

    Of course. What you really need is a vector with 4096 elements, not 4096 (empty) vectors.

    class Memory {
    private:
        vector<uint8_t> workingMemory;  
    public:
        Memory(){workingMemory.resize(4096);}
        void addToMemory(vector<uint8_t>& gameData);
        void print();
    };
    

    I’d also like to use a unique_ptr<Memory> to manage the Memory class is that a good idea in this context?

    Once you have rewritten your class correctly, this is no longer necessary.