How do I fix an Access Violation Error in C++

65 views Asked by At

I have an assignment in which I have to take an array and reverse it's order. We are supposed to use pointers to accomplish this but I'm having trouble with one part of my code. On line 26 I'm trying to reassign the array element to a new value but when I try I get an Access Violation Error "Unhandled exception at 0x00007FF60459600D in HW7_JacobS.exe: 0xC0000005: Access violation writing location 0x0000000000000000."

#include <stdio.h>
#define SIZE 10

void swap_elements(int *array, size_t size);

int main(void) {
    puts("Enter elements of the array and the code will reverse the array.");
    int array[SIZE];
    for (int i = 0; i < SIZE; i++) {
        printf("Enter element %d: ", i);
        scanf("%d", &array[i]);
    } 
    puts("Array before reversing:");
    for (int i = 0; i < SIZE; i++) {
        printf("%5d", array[i]);
    } puts("");
    swap_elements(*array, SIZE);
 }

void swap_elements(int *array, size_t size) {
    for (int i = 1; i <= size / 2; i++) {
        int *element1Ptr = &array[i - 1];
        int *element2Ptr = &array[-1];
        int val1 = element1Ptr;
        int val2 = element2Ptr;
        array[i - 1] = val1; // Here is the problem
        array[-i] = val2;
    }
    puts("Array after reversing:");
    for (int i = 0; i < SIZE; i++) {
        printf("%5d", array[i]);
    }
}

I was expecting the code to reassign array[i - 1] to val1 but instead the code breaks and gives this error in debug mode.

1

There are 1 answers

0
Swift - Friday Pie On

This is C code, and you likely compile it as C if your file had .c extension. swap_elements(*array, SIZE); is giveaway, result of *array is an intad you're trying tocast if from pointer. A C compiler will tell you:

prog.c:18:19: warning: passing argument 1 of 'swap_elements' 
makes pointer from integer without a cast [-Wint-conversion]

From here on your code WILL cause UB, e.g. address violation, becuase swap_elements accesses some non-existing object.

In C++ this code won't compile at all because of multiple errors.

While array[-i] is a correct syntax , it assumes *(array-i) being a correct location, but in your case array points at the beginning of array. Negative index in C and C++ doesn't do what it does in Python.