[英]C program unexpectedly crashes after giving correct output
我正在嘗試編寫一個簡單的C程序來反轉字符串。 代碼如下:
void swap(char* a, char* b){
char* temp;
*temp = *a;
*a = *b;
*b = *temp;
}
char* reverseString(char* str){
int length = strlen(str);
int i=0;
for(i=0; i<(length/2); i++){
swap(&str[i], &str[length-i-1]);
}
return str;
}
int main(){
char str[] = "Hello World";
reverseString(str);
printf("%s\n",str);
return 0;
}
它確實打印正確的結果,但隨后發出了SEGMENTATION FAULT。 它發生在主函數的“ return 0”語句上。
您能幫我弄清楚為什么發生SEG故障。
謝謝。
在您的swap()
函數中,問自己:
void swap(char* a, char* b){
char* temp;
問: temp
現在指向哪里?
答:未知,可能在某個地方很危險。
*temp = *a;
但是我們只是在那個地方寫了一些東西。
而是使用char
:
void swap(char* a, char* b){
char temp;
temp = *a;
*a = *b;
*b = temp;
}
您調用未定義的行為,這就是代碼似乎可以正常運行的原因,但是它實際上並沒有正常工作,這是您遇到的問題
void swap(char* a, char* b) {
char *temp;
*temp = *a;
*a = *b;
*b = *temp;
}
您將temp
聲明為char
指針,然后在它是無效指針時取消引用它,正確的方法是
void swap(char* a, char* b) {
char temp;
temp = *a;
*a = *b;
*b = temp;
}
你也可以做到
void swap(char* a, char* b) {
char temp[1];
*temp = *a;
*a = *b;
*b = *temp;
}
這沒有多大意義,但是可以工作,或者您甚至可以這樣做
void swap(char* a, char* b) {
char *temp;
temp = malloc(1);
if (temp != NULL)
{
*temp = *a;
*a = *b;
*b = *temp;
free(temp);
}
}
這沒有什么意義,但也可以使用,要點是向您顯示使用間接運算符*
,指針必須有效。
因此,程序崩潰的原因是無效的指針取消引用導致的未定義行為。
在交換函數中,要么使用int temp,要么使用int temp。
void swap(char *a, char *b)
{
char temp;
temp = *a;
*a = *b;
*b = temp;
}
或將int * temp = NULL設置為不指向未知內存。
void swap(char *a, char *b)
{
char *temp = NULL;
*temp = *a;
*a = *b;
*b = *temp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.