Home > Mobile >  C read access violation - Pointers
C read access violation - Pointers

Time:12-05

I'm new to C and I'm getting a little tangled up with the Visual Studio Code.

I did not understand what that meant.

When I run the code in another compiler it does run.

'''

    void swap(int* x, int *y);
    int exe1(int* num1Ptr, int* num2Ptr, int* num3Ptr);

    int main()

    {
    int a = 123, b = 456 , c =4;
    int* pa, * pb ,*pc;
    pa = &a;
    pb = &b;
    pc = &c; 

    printf("pa = %d , pb = %d, pc = %d\n", *pa, *pb, *pc);
    exe1(pa, pb, pc);
    printf("pa = %d , pb = %d, pc = %d\n", *pa,*pb,*pc);
    



    return 0;
   }


    void swap(int* x, int* y) {
    int temp = *x; 
    *x = *y;
    *y = *x; 
}


    int exe1(int* num1Ptr, int* num2Ptr, int* num3Ptr) {
    if (*num2Ptr > *num1Ptr) {
        swap(*num1Ptr, *num2Ptr);
    }
    if (*num3Ptr > *num2Ptr) {
        swap(*num3Ptr, *num2Ptr);
    }
    if (*num3Ptr > *num1Ptr) {
        swap(*num3Ptr, *num1Ptr);
    }
    

CodePudding user response:

void swap(int* x, int* y) {
int temp = *x; 
*x = *y;
*y = *x;  // this should be *y = temp;
}

CodePudding user response:

Your swap routine expects two pointers to int and you pass two ints to it. Remove superfluous asterisks from the calls:

swap(*num1Ptr, *num2Ptr);

should read

swap(num1Ptr, num2Ptr);

Plus the mistake inside swap() which Kaitou points out in the answer.

CodePudding user response:

"read access violation" occurs when we try to access a memory address which we don't have access to. In this case it is because of swap(*num1Ptr, *num2Ptr);

This function expects a pointer (relating to memory address) and should be called as swap(num1Ptr, num2Ptr);

*num1Ptr dereferences the pointer, it is now an integer value, not a pointer to a valid address. For example *num1Ptr can be 123 in the above code. Whatever sits at memory address 123 is probably used by system and we don't have read/write access to it. Debugger throws access violation.

The compiler should also print warnings.

The swap function needs a fix *y = temp; as noted earlier.


Unrelated to your question, exe1 compares values in this order

p1 & p2 
p2 & p3 
p1 & p3

If this were intended as a sort function for example, the third condition can negate the first condition. You may want to change the order of comparison as shown below:

void swap(int* x, int* y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}

void exe1(int* p1, int* p2, int* p3)
{
    if (*p1 < *p2) swap(p1, p2);
    if (*p1 < *p3) swap(p1, p3);
    if (*p2 < *p3) swap(p2, p3);
}

int main()
{
    int a, b, c;
    a = 123, b = 456, c = 4;
    exe1(&a, &b, &c); printf("%d, %d, %d\n", a, b, c);
    a = 123, b = 456, c = 4000;
    exe1(&a, &b, &c); printf("%d, %d, %d\n", a, b, c);
    return 0;
}
  • Related