简体   繁体   中英

Error in the program to swap two numbers using Pointers

A few years back i was working with Turbo C compiler and the following code worked fine on it.

#include<stdio.h>
void main()
{
     int a=2,b=3;
     swap(a,b);
     printf("%d\n%d\n",a,b);
}

swap(int *x,int *y)
{
     int t;
     //x=malloc(2);
     //y=malloc(2);
     t=*x;
     *x=*y;
     *y=t;
     printf("%d\n%d\n",x,y);
}

Now i am working on cygwin and if i run this code i get an error Segmentation fault(core dumped) If i uncomment the malloc statements i get the output

536937064
536937080
2
3

Are first two lines of output some garbage values? What exactly is happening here and how can i get the correct output?

Here is the corrected version of your program, which will execute correctly.

There are a number of things going wrong in the sample you posted:

Incorrect Argument type being passed:

swap(a,b); 

should be :

swap(&a,&b); 

Your function expects pointer to the integers to be modified, You are not doing so.


Incorrect Format specifiers for printf :

printf("%d\n%d\n",x,y); 

should be:

printf("%d\n%d\n",*x,*y); 

printf is not type safe and you need to ensure you use proper format specifiers while using it. Using incorrect format specifiers results in Undefined Behavior .


The next two are good practices if not errors and you should follow them.

Incorrect return type of main() :

As per the Standard a program should return int ,

void main()

should be

int main()

Also, add return a value return 0; at the end of main .


Function Declaration:

You should declare the function swap() correctly before main :

void swap(int *x,int *y); 

Providing a function declaration before the place where you use it in code, gives the compiler a opportunity to match the parameters and report incorrect types being passed.


Further using malloc as you have would not acheive what you are trying to achieve, You do not need to use malloc here at all and One should always avoid using it as much as possible.

Also, You should pick up a good book and learn the basics.

Nothing here is actually correct.

  1. The parameters to swap are the literal addresses 2 and 3. You can &a and &b in the call.
  2. printf in swap is printing the pointer addresses, so the output is "expected".
  3. If you were using malloc (why?), you are only allocating 2 bytes. An int is generally 4 , but please use sizeof .

You are passing values of the variables and using pointers to receive it.

`swap(a,b) `

should be swap(&a,&b)

because you must pass the address of the variables, not the variable itself. Read Call by reference in C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM