[英]Weird Segmentation Fault after printing
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 ? 我应该简单地忽略这一点并继续前进吗,还是真的有奇怪的事情发生?
int* temp; *temp = *p1;
is undefined behaviour in C and C++ as you are using an uninitialised pointer. 在C和C ++中是未定义的行为 ,因为您使用的是未初始化的指针。 (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;
使用
int temp; temp = *p1;
int temp; temp = *p1;
instead, or better still, int temp = *p1;
相反,或者更好的是,
int temp = *p1;
This should work: 这应该工作:
( temp
is a normal int
! Otherwise your using a uninitialized pointer which is undefined behaviour) (
temp
是一个普通的int
!否则,您将使用未初始化的指针,这是未定义的行为)
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.