-2

Why this code is showing Segmentation fault (core dumped)?

#include<stdio.h>

void swap(int*,int*);

int main(){
    int x=5,y=10;
    swap(&x,&y);
    printf("%d%d",x,y);
    return 1;
}

void swap(int *a,int *b){
    int *temp;
    *temp = *a;
    *a = *b;
    *b = *temp; 
}
sergej
  • 17,147
  • 6
  • 52
  • 89
shahbaz17
  • 33
  • 5
  • 2
    Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Oct 15 '15 at 17:32

3 Answers3

5

int *temp; is the problem. It is not pointing to any memory that you own. The behaviour on dereferencing temp is undefined.

Use int temp; instead, (preferably int temp = *a; since then temp is never in an uninitialised state) and temp rather than *temp in the assignments.

(By the way, 0 is conventionally the return value from main that indicates success.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

In swap() function you declare a pointer (int *temp;) and just after you dereference it using (*temp = ...). At initialization temp contains nothing (well, probably 0, but whatever), and '*temp' means "the integer that is at address contained in temp".

Here you want to manipulated an int:

void swap(int *a, int *b) {
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
}
hexasoft
  • 677
  • 3
  • 9
0
`int *temp;`

This statement just creates a pointer to a integer. So, before

*temp = *a;  

You need to allocate a memory to which temp will point. otherwise temp will have some junk value that will make it a pointer to a random location. So if you are using int *temp then allocate memory before using or you can use int variable int temp;

LearningC
  • 3,182
  • 1
  • 12
  • 19