-2

I am writing code to write a vector to file. My aim is to write the last half of the vector to file first and then the first half based on offset. The code below gives me segmentation fault.

std::vector<uint8_t> buffer_(1000); // the vector is filled with values
int offset_ = 300;
std::ofstream output_file (file_name.c_str(), std::ofstream::out | std::ofstream::binary);
if (output_file.is_open()) {
    output_file.write(reinterpret_cast<const char*>(&buffer_[offset_]), (buffer_.size() -offset_)*sizeof(uint8_t));
    // segmentation fault on the line above
    output_file.write(reinterpret_cast<const char*>(&buffer_[0]), (offset_)*sizeof(uint8_t));
}

Can somebody tell me whats wrong with the code?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
Yogesh patel
  • 1,351
  • 2
  • 15
  • 21

2 Answers2

4

You start by treating the offset as a [0-based] array index (&buffer_[300]) but then immediately treat it as a [1-based] element count (buffer_.size()-300). This is going to result in reading 700 elements starting at the 301st element, which goes past the end of your vector by one element.

Subtract one from either of the arguments, depending on what you actually mean by "offset".

You should get used to working out this basic maths on paper when you have a problem.
Using your debugger wouldn't hurt, either!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The functionality sought by this question is already implemented in rotate and rotate_copy. As a general rule re-implementing behavior already in the standard is wasteful and/or can be fraught with error, as is demonstrated by this question.

Since rotate_copy only uses ForwardIterators for it's input iterators, this answer can be leveraged through the simple use an ostreambuf_iterator. So this can be done instead of the two writes in the question:

const char* pBufferBegin = reinterpret_cast<const char*>(&*buffer_.data());

rotate_copy(pBufferBegin, pBufferBegin + offset_, pBufferBegin + buffer_.size(), ostreambuf_iterator<char>(output_file));
Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    Nice, except your output is not quite right; the OP appears to want to write the binary representations of his `uint8_t`s to disk, not ASCII representations of the same. – Lightness Races in Orbit Aug 11 '15 at 12:45
  • @LightnessRacesinOrbit Ugh, you're totally right. I've tinkered with my answer, but I can't come up with a way to stream Unformatted Output. In the end I concede that use of the standard's implementation is probably not the best solution here :( I'd give your answer a +1 but I've already done that ;) – Jonathan Mee Aug 17 '15 at 12:25