Need help on this code...(Segmentation Fault)
Hi all,
When I was compiling this code in Linux with g++, I got the Segmentation Fault. I guess I might have
misused the pointer in my function. Could you help me figure out what's wrong with my code?
What this code should do is swapping the values of int a and int b with function swap...
Code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
void swap(int *p, int *q)
{
int *temp;
*temp=*p;
*p=*q;
*q=*temp;
}
int main()
{
int a=5,b=10;
int *p=&a;
int *q=&b;
swap(p,q);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
return 0;
}
Re: Need help on this code...(Segmentation Fault)
You have created a pointer, temp, pointing to nothing in particular. You then attempt to write to the location it points to (nowhere in particular).
Re: Need help on this code...(Segmentation Fault)
Oh, yea...
I changed the code to something like this, then it works. Thank you Lindley.
Code:
void swap(int *p, int *q)
{
int temp;
temp=*p;
* p= *q;
* q= temp;
}
Re: Need help on this code...(Segmentation Fault)
Alternatively, to get rid of that pesky temp!
Code:
void swap(int *p, int *q)
{
*p = *p - *q;
*q = *q + *p;
*p = -(*p - *q);
}
Shush your complaints! I just like it.
Re: Need help on this code...(Segmentation Fault)
Quote:
Originally Posted by
Moschops
Alternatively, to get rid of that pesky temp!
[...]
:eek: :cool:
Where did you find that? Obfuscated C Contest? :D
No, seriously, aside from saving the stack space for temp it doesn't seem to be more efficient.
Re: Need help on this code...(Segmentation Fault)
While a neat mathematical trick, it seems more likely to be less efficient in most cases. Assuming, of course, that the types being swapped even support the operation.
Re: Need help on this code...(Segmentation Fault)
Re: Need help on this code...(Segmentation Fault)
The swap obfuscated swap I've always been taught is:
Code:
template<typename POD_t>
void swap(POD_t& lhs, POD_t& rhs)
{
lhs^=rhs;
rhs^=lhs;
lhs^=rhs;
}
It works for the same reasons it works with operator-. This has the advantage of working on ANY pod type. On non POD types there are no guarantees (ie assume it doesn't work).
In the real world, this is not very efficient, as pretty much every processor now has a single instruction swap built in (explicitly or implicitly).
If you want more C++ bitwise "tricks", you can always go to http://www-graphics.stanford.edu/~seander/bithacks.html
Back to the topic at hand, this is how swap is usually implemented.
Code:
template <class T>
void swap(T& a, T& b)
{
T c(a);
a=b;
b=c;
}
Notice the complete lack of pointers. Pointers are evil.
Re: Need help on this code...(Segmentation Fault)
With C++0x, I suspect it would instead be:
Code:
template <class T>
void swap(T& a, T& b)
{
T c(move(a));
a=move(b);
b=move(c);
}