Weird Segmentation Fault after printing

纵饮孤独 提交于 2019-12-13 08:24:57

问题


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 ?


回答1:


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;




回答2:


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;
}


来源:https://stackoverflow.com/questions/26968935/weird-segmentation-fault-after-printing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!