首页 > 解决方案 > Segmentation fault (core dumped) 执行代码时出错

问题描述

执行代码时需要帮助找出分段错误(核心转储)的原因。我试图研究原因,但没有发现与我的代码有关的任何东西。对不起,对于编程来说仍然是新的糟糕代码

#include <stdio.h>
int main(void)
{
char str[1000];
int counta , counte, counti,counto,countu;
int q =0;
    printf("Enter a String: \n");
    scanf("%s" , str);



//if (feof(stdin)) break; //CRTL D TO STOP


    while(1==1 && str[q] != 1000 ) {

    if(str[q] == 'a')
    {
            q++;
            counta++;
    }
    else q++;

    }
    q = 0;

    //while(str[q]

 printf("%d" , counta);


return 0;

}

标签: ccygwin

解决方案


您的程序有一个带有条件的 while 循环 -

while (1==1 && str[q] != 1000) 

1==1是没用的,因为 1 总是等于 1。 thestr[q] != 1000也将永远为真,因为str[q]它的类型char不能保存值1000

因此,您的程序进入无限循环。因此,它最终访问了超出str. 并且这里的行为没有定义。大多数情况下,您的程序会崩溃。

你可能的意思是条件是 -

while ( q != 1000)

这将起作用并且不会导致任何未定义的行为,但请注意字符串在数组总长度之前结束。字符串在遇到'\0'字符时结束。你应该使用条件 -

while ( q < 1000 && str[q] != '\0')

另外,请确保不要切换条件的顺序,否则您将再次读取超出范围的内存。


推荐阅读