简体   繁体   English

反转字符串时发生分段错误

[英]segmentation fault occur while reversing the string

Below is my piece of code, I don't understand why it always gives me the segmentation fault: 下面是我的代码,我不明白为什么它总是给我分段错误:

#include <stdio.h>
void reverse(void);

int main ()
{
    printf("enter the text");
    printf("\n");
    reverse(); 

    printf("\n");
    return(0);
} 
void reverse(void)
{
    char c;
    if((c=getchar()) != '\n')
    {
        reverse();
    }
    putchar(c);
}

In my opinion I have done everything correctly, what is the mistake? 我认为我已正确完成所有操作,这是什么错误?

The code works fine as long as you enter a newline. 只要输入换行符,代码就可以正常工作。 Perhaps you are terminating your input with EOF (usually bound to Ctrl+D) without feeding it a newline before, and in that case, the code will never see a newline and there will be a stack overflow due to infinite recursion. 也许您正在使用EOF终止输入(通常绑定到Ctrl + D)而之前没有输入换行符,在这种情况下,代码将永远不会看到换行符,并且由于无限递归而导致堆栈溢出。

So, you should check that getchar() doesn't return EOF . 因此,您应该检查getchar()不返回EOF Also, getchar() returns int , not char - this is important for portability and to make sure that comparison with EOF works as expected. 同样, getchar()返回int ,而不是char ,这对于可移植性以及确保与EOF比较能够按预期进行很重要。

Here's the code after addressing these issues: 解决这些问题后的代码如下:

#include <stdio.h>

void reverse(void);

int main (void) {
    printf("enter the text\n");
    reverse(); 
    printf("\n");
    return 0;
}

void reverse(void) {
    int c;
    if ((c=getchar()) != '\n' && c != EOF) {
        reverse();
    }
    if (c != EOF) {
        putchar(c);
    }
}

Your program compiled and ran fine on my setup: latest stable gcc on Ubuntu 14.04.2 LTS 64-bit. 您的程序已编译并在我的设置上运行良好:Ubuntu 14.04.2 LTS 64位上的最新稳定版gcc。

Here is another version using a different approach (namely the fgets function). 这是另一个使用不同方法的版本(即fgets函数)。 See if it works for you: 看看是否适合您:

#include <stdio.h>
#include <string.h>

void reverse_str( char * );

int main()
{
    char input[1024];

        printf("Enter text: ");
        fgets(input, sizeof(input), stdin);

        reverse_str(input);

        printf("Reversed string: %s\n", input);

    return 0;
}

void reverse_str(char *to_reverse)
{
    char temp[1024];
    int count = strlen(to_reverse) - 1; //Exclude newline introduced with fgets
    int i=0;

        for( i=count; i>=0; i-- ){
            temp[i] = to_reverse[count - i - 1]; //Subtract 1 to not include the new line introduced by fgets
        }

        temp[count+1] = '\0';
        strcpy(to_reverse, temp);
}

Your code seems to failing because of the nasty characters of getchar()..In most of the system it should work but I think your compiler is trying to access the memory saved beyond the array & hence generating segmentation fault...Can you please make sure if you give '\\0' in place of '\\n', it is working or not..I think the problem is that your machine is not able to detect the '\\n' given from your keyboard & hence keep on going into recursion mode & stack is overflown before the recursion ends & when stack is overflown, it is trying to access unauthorised memory & hence segmentation fault occurs 由于getchar()的令人讨厌的字符,您的代码似乎失败了。在大多数系统中,它应该可以工作,但我认为您的编译器正在尝试访问数组之外​​保存的内存,从而产生分段错误。确保是否用'\\ 0'代替'\\ n',它是否正常工作。我认为问题是您的计算机无法检测到键盘上的'\\ n',因此请继续进入递归模式,并且在递归结束之前堆栈已溢出;当堆栈溢出时,它试图访问未授权的内存,因此发生分段错误

Try this 尝试这个

#include <stdio.h>
#include <string.h>
char str[] = "Hello World";
size_t length;
int count = 0;

void reverse(char* a, char* b){
//  static int count = 0;
  char temp;
  if (count < length/2){
    count++;
    reverse(str + count, str + (length - 1) - count);
  }
    temp = *a;
    *a = *b;
    *b = temp;
}
int main(){
length = strlen(str);
reverse(str, str + length - 1);
printf("%s", str);
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM