You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:在C语言中反转字符串时遭遇Segmentation Fault(段错误)

Fixing Segmentation Fault & Correcting String Reversal in C

Hey there! Let's walk through the issues in your code that's causing the segmentation fault and get your string reversal working properly.

First: The Root Cause of the Segmentation Fault

In your main function, you're passing a string literal ("ABCDE") to my_revstr. String literals in C are stored in read-only memory sections—any attempt to modify them (which your function tries to do) triggers undefined behavior, and a segmentation fault is a common result here.

To fix this, you need to pass a modifiable character array instead:

int main() {
    char str[] = "ABCDE"; // This creates a writable array containing the string
    my_revstr(str);
}

Second: Broken Logic in my_revstr

Your current reversal logic is incorrect and contributes to the crash too. Let's break down what's wrong:

  • ptr += ptr[i]: This is invalid pointer arithmetic—you're adding the ASCII value of the character at ptr[i] to the pointer, which sends it flying to an arbitrary memory address (hence the segfault).
  • str[i] = str[(len/2)-1]: This doesn't swap characters; it's just overwriting the i-th character with the middle character of the string, which isn't what reversal does.

Correct Reversal Logic

The standard approach for reversing a string is to swap characters from the start and end of the string, moving towards the center. Here's how to fix my_revstr:

void my_revstr(char str[]) {
    int len = my_strlen(str);
    char temp;
    // Use two indices: one starting at the beginning, one at the end
    for (int i = 0, j = len - 1; i < j; i++, j--) {
        // Swap str[i] and str[j]
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    printf("%s\n", str); // Add newline for cleaner output
}

How This Works

  • i starts at 0 (first character), j starts at len-1 (last character, since strings are 0-indexed).
  • We swap the characters at these positions, then increment i and decrement j.
  • We stop when i >= j—this means we've swapped all pairs and reached the middle of the string.

Full Corrected Code

Putting it all together, here's the working version:

#include <stdio.h>

int my_strlen(char const str[]){
    int i = 0;
    int count = 0;
    while (str[i] != '\0'){
        count++;
        i++;
    }
    return count;
}

void my_revstr(char str[]) {
    int len = my_strlen(str);
    char temp;
    for (int i = 0, j = len - 1; i < j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    printf("%s\n", str);
}

int main() {
    char str[] = "ABCDE";
    my_revstr(str);
}

This will output EDCBA as expected, with no segmentation faults.

内容的提问来源于stack exchange,提问作者TheTricky65

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:47:48