-1

Wrote a simple swap program, works well; But gives a Segmentation Fault after printing everything.

#include <stdio.h>

void swap(int* p1,int* p2){

    int* temp;
    *temp = *p1;
    *p1 = *p2;
    *p2 = *temp;
}

int main(){ 

    int a,b;
    a = 9; b = 8;
    printf("%d %d \n",a,b);
    swap(&a,&b);    
    printf("%d %d \n",a,b);

    return 0;
}

Output:

9 8  
8 9  
Segmentation fault

Should I simply ignore this and move forward or is there something really strange going on ?

Leero
  • 57
  • 2
  • 8

2 Answers2

2

int* temp; *temp = *p1;

is undefined behaviour in C and C++ as you are using an uninitialised pointer. (At the point of use, a pointer must always point to memory that you own, and your pointer isn't).

Use int temp; temp = *p1; instead, or better still, int temp = *p1;

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    That's the nature of *undefined behaviour*. Sometimes it works, sometimes it doesn't. Sometimes it eats your cat. – Bathsheba Nov 17 '14 at 09:07
  • @Leero It's always a surprise what undefined behaviour does :D (Thats why it's called: 'undefined behaviour') – Rizier123 Nov 17 '14 at 09:08
0

This should work:

(temp is a normal int! Otherwise your using a uninitialized pointer which is undefined behaviour)

#include <stdio.h>

void swap(int* p1,int* p2){

    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;

}

int main(){ 

    int a = 9, b = 8;

    printf("%d %d \n",a,b);
    swap(&a, &b);    
    printf("%d %d \n",a,b);

    return 0;
}
Rizier123
  • 58,877
  • 16
  • 101
  • 156