user3880587
user3880587

Reputation: 69

Getting segmentation faults when flipping image

When I'm running this code, I keep getting segmentation faults. I know segmentation faults occur when there's not enough memory allocated to the array. Does anybody know where the seg fault is occuring at?

void flip_horizontal( uint8_t array[], 
              unsigned int cols, 
              unsigned int rows )
{
    for(int r = 0; r < rows; r++)
    {
        unsigned int left = 0;
        unsigned int right = cols;
        int* array = malloc(sizeof(uint8_t));
        assert(array);
        while(left != right && right > left)
        {
            int temp = array[r * cols+ left];
            array[(r * cols) + left] = array[(r * cols) + cols - right];
            array[(r * cols) + cols - right] = temp;
            right++;
            left++;
        }
        free(array);
    }
}

Upvotes: 0

Views: 93

Answers (2)

iRonhead
iRonhead

Reputation: 1

int* array = malloc(sizeof(uint8_t));
......
free(array);

You allocated memories, assigned its address to 'array' and the size of memory is only 1 byte. There is only 1 byte while 'cols' may be greater than 1, the size of memory is not large enough. Remove those 2 lines can fix the first issue. BTW, the variable 'array' should not be changed and you don't need a buffer to flip.

Besides, the left, right and swapping loop should be:

unsigned int left = 0;
unsigned int right = cols - 1;

while(left < right) {
  int temp = array[r * cols + left];
  array[r * cols + left] = array[r * cols + right];
  array[r * cols + right] = temp;

  right--;
  left++;
}

Upvotes: 0

nneonneo
nneonneo

Reputation: 179522

You made a very simple error. Your left and right indices should be moving towards each other; instead, you're incrementing both of them inside your loop.

Upvotes: 3

Related Questions