My program is working properly but still at the end its showing Segmentation fault

94 views Asked by At
  • gdb already Tried :0
void Reverse(struct Array *arr)
{
    int i, j;
    for (i = 0, j = arr->length - 1; i < j; i++, j--)
    {
        swap(&arr->arr[i], &arr->arr[j]);
    }
}

void Reverse2(struct Array *obj)
{
    int *b;
    int i, j;
    b = new int;
    for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
        b[j] = obj->arr[i];
    for (i = 0; i < obj->length; i++)
        obj->arr[i] = b[i];
}

void Display(struct Array obj1)
{
    int i;
    cout << "yOur elements are: ";
    for (i = 0; i < obj1.length; i++)
        cout << obj1.arr[i] << " ";
}

int main()
{
    struct Array obj = {{9, 8, 7, 6, 5, 3}, 10, 6};
    cout << "your array is: ";
    Display(obj);

    cout << "\nAfter reversing using swap ";
    Reverse(&obj);
    Display(obj);

    cout << "\nAfter reversing: ";
    Reverse2(obj);
    Display(obj);

    return 0;
}

This is the output

  • your array is: yOur elements are: 9 8 7 6 5 3
  • After reversing using swap yOur elements are: 3 5 6 7 8 9
  • After reversing: yOur elements are: 3 5 6 7 8 9 Segmentation fault
1

There are 1 answers

2
john On BEST ANSWER

Your code allocates a single integer, but then treats that integer as an array. Here

b = new int;
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
    b[j] = obj->arr[i];

should be

b = new int[obj->length];
for (i = obj->length - 1, j = 0; i >= 0; i--, j++)
    b[j] = obj->arr[i];