Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 执行代码时出现分段错误(堆芯转储)错误_C_Cygwin - Fatal编程技术网

C 执行代码时出现分段错误(堆芯转储)错误

C 执行代码时出现分段错误(堆芯转储)错误,c,cygwin,C,Cygwin,当我执行代码时,需要帮助找出分段错误(内核转储)的原因。我试图研究原因,但没有发现与我的代码有关的任何东西。很抱歉,对于编程来说,糟糕的代码仍然是新的 #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); //i

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

#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;
#包括
内部主(空)
{
char-str[1000];
int counta,counte,counti,counto,countu;
int q=0;
printf(“输入字符串:\n”);
scanf(“%s”,str);
//如果(feof(stdin))中断;//CRTL D停止
而(1==1&&str[q]!=1000){
如果(str[q]=“a”)
{
q++;
counta++;
}
else-q++;
}
q=0;
//while(str[q]
printf(“%d”,counta);
返回0;

}您的程序有一个while循环,循环条件为-

while (1==1 && str[q] != 1000) 
while ( q < 1000 && str[q] != '\0')
1==1
是无用的,因为1总是等于1。
str[q]!=1000
也总是真的,因为
str[q]
char
类型,它不能保存值
1000

因此,您的程序进入无限循环。因此,它访问的内存超出了
str
的界限。这里的行为没有定义。在这种情况下,您的程序通常会崩溃

你的意思可能是-

while ( q != 1000)
这将起作用,不会导致任何未定义的行为,但请注意,字符串在数组总长度之前结束。字符串在遇到
'\0'
字符时结束。应使用以下条件-

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

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

str[q]
永远不会等于
1000
。您的程序将进入无限循环并访问越界内存。您可能是指
q<1000