1

I have a small segment of C++ code that reads in unsigned char's a block at a time and then for debugging purposes, outputs via std::cout

int fd;
ssize_t bytes_read {0};
unsigned char *buffer {new unsigned char[512]};
std::vector<unsigned char> *pMemory {new std::vector<unsigned char>(512)};

fd = open("/tmp/text.txt", O_RDONLY);
if (fd != -1)
{
    do
    {
        bytes_read = read(fd, buffer, 512);
        if (bytes_read > 0)
        {
            for (int i = 0; i < bytes_read; ++i) {
                pMemory->emplace_back(buffer[i]);
            }
        }
    } while (bytes_read > 0);

    for (auto const& block : *pMemory)
    {
        std::cout << block;
    }

    std::cout << std::endl;
}

I have initialized the vector pMemory with a block to prevent memory thrashing from each call to pMemory->emplace_back(buffer[i]), but I am wondering if there is a more efficient way (perhaps by using iterators to move a range from the buffer array ?), to move each chunk of memory in buffer into a vector ?

S Davies
  • 13
  • 3

1 Answers1

0

You can make your code simpler by using insert:

pMemory->insert(pMemory->end(),buffer,buffer+bytes_read);

It may or may not make it faster though. If performance is an issue, you'll need to measure.

Note that you don't want your vector to start with 512 bytes (like you have now), you just want to reserve 512 bytes, like this:

std::vector<unsigned char> *pMemory = new std::vector<unsigned char>;
pMemory->reserve(512);

But you don't need to use new at all:

unsigned char buffer[512];
std::vector<unsigned char> memory;
memory.reserve(512);

.
.
.

memory.insert(memory.end(),buffer,buffer+bytes_read);

If you just want to read a file into a vector, you may want to look at this question though: Efficient way of reading a file into an std::vector<char>?

Community
  • 1
  • 1
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • But without `new`, won't the `vector` be allocated on the stack ? Or is the `memory` variable allocated on the stack and `vector` allocates the memory for the contents of the vector on the heap for me ? – S Davies Dec 25 '15 at 03:02
  • @SDavies: A vector has two parts. There is a (small) part that will be on the stack, which is just a few pointers. Those pointers will point to heap memory that the vector manages, as you guessed. – Vaughn Cato Dec 25 '15 at 03:04
  • Ah, ok! Thanks for your help. – S Davies Dec 25 '15 at 03:07