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:
should be :
Your function expects pointer to the integers to be modified, You are not doing so.
Incorrect Format specifiers for
printf:should be:
printfis 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,should be
Also, add return a value
return 0;at the end ofmain.Function Declaration:
You should declare the function
swap()correctly beforemain: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
mallocas you have would not acheive what you are trying to achieve, You do not need to usemallochere 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.