Search code examples
c++segmentation-faultflipfault

Segfault from hflip


For some reason when I run this code I get a segfault. What it does is reads a PGM file from input and flips it horizontally.

Here is what I believe is the offending code:

for (i = pixels.size()-1; i = 0; i--){ // this loop takes the final value of the original vector and puts it into the first spot in the new hflip vector, and continues onwards
    flippy.push_back(pixels[i]);
}

cout << "P2" << endl << numColumns << " " << numRows << endl << "255" << endl;
while (p < pixTotal){
    for (int z = 0; z < numRows; z++){
        cout << flippy[p] << " ";
    }
    cout << endl;
    p++;

}

Solution

  • I assume the vector pixels represents each row in your matrix. Then to flip all values in the vector, you can simply use std::reverse_copy like this:

    std::vector<uint8_t> flippy;
    flippy.resize(pixels.size());
    std::reverse_copy(pixels.begin(), pixels.end(), flippy.begin());
    

    You need to do this for each row. You can then output each flipped row after each reverse so that the vector 'flippy' only represents the current row in operation.