Home > database >  Why is my program snapping out abruptly without any error?
Why is my program snapping out abruptly without any error?

Time:11-03

My code is running weirdly due to some runtime error in pointer part. This is my code which is acting weird because I made mistake.

#include<stdio.h>
void swap(int*, int*);
int main()
{
    int a, b;
    printf("Enter the value of a : ");
    scanf("%d",&a);
    printf("Enter the value of b : ");
    scanf("%d",&b);
    swap(&a,&b);
    printf("Values of a and b after swapping are %d and %d respectively\n",a,b);
}
void swap(int *a, int *b)
{
    int *temp;
    printf("asdf");
    *temp=*a;
    printf("asdf");
    *a=*b;
    *b=*temp;
}

and the ouput is Enter the value of a : 5 Enter the value of b : 2 asdf I mistakenly made temp a pointer variable instead of simple integer variable. But why does my code doesn't work any further and ends up right there?

CodePudding user response:

In swap, temp is an uninitialized pointer, so you're corrupting memory. But it shouldn't be a pointer at all. Change it to:

void swap(int *a, int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

The reason the original code behaves oddly is because it's storing to the target of an uninitialized pointer. That pointer could contain any value, so writing to its target could change any part of memory. This is known as undefined behavior. For example, it could modify a return address, or some other variable. The behavior is specific to the particular compiler you're using, the options that are in effect, etc. If you really want to know what's going on with a particular compiler, you'd need to look at the assembly code and the call sequence to see exactly what that uninitialized pointer contains and what effect modifying its target will have.

CodePudding user response:

why does my code doesn't work any further and ends up right there?

Your swap function makes the program have undefined behavior:

void swap(int *a, int *b)
{
    int *temp; // an uninitialized pointer - no memory allocated

    *temp=*a;  // assigning to *temp - and temp may be pointing anywhere

    *a=*b;
    *b=*temp;
}

The above assignment is what causes the problem. When a program has undefined behavior, anything can happen - like the sudden termination of the program.

  • Related