vopi181
vopi181

Reputation: 13

How to copy a vector to a subvector of another vector without segfaulting?

I have some code that looks like this:

for (int = i; i > (chip.rom.size() - 1); i++) {
        //int i = 0;
        chip.memory[i + 512] = chip.rom[i];
        //i++;

}

chip is a struct where memory and rom are both vectors of unsigned chars

rom is a vector of 160 bytes which is the game rom that I'm using to test my emulator.

memory is zeroed to 4096 bytes like so:

chip.memory = std::vector<BYTE>(4096);

Upon debugging, I managed to found out that I was seg faulting after this for statement. I feel like im going crazy! What obvious error am I missing?

Upvotes: 1

Views: 134

Answers (1)

Omnifarious
Omnifarious

Reputation: 56038

You don't initialize i and your comparison is in the wrong direction. Also, if you use < for your comparison, the - 1 is unnecessary if you're just trying to avoid running off the end of chip.rom.

You shouldn't even be using a loop at all here really. Here's how the code ought to read:

#include <algorithm>  // Somewhere up above

::std::copy(chip.rom.begin(), chip.rom.end(), chip.memory.begin() + 512);

Use the stuff from the <algorithm> header and you don't have to remember to get everything in your for statement correct all the time. Not only that, but it's likely your compiler will generate more efficient code.

Upvotes: 3

Related Questions