简体   繁体   English

带有数组的分段错误(核心转储)C 程序

[英]Segmentation Fault (Core Dumped) C Program with Arrays

#include <stdio.h>
#include <string.h>
#define SIZE 1000

int main(void)
{
char sent[] = "\0";        
char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
unsigned int count;
unsigned int k;
unsigned int j;                                                            

printf("Please enter a sentence to analyze\n");
fgets(sent, SIZE, stdin);  


printf("\n     Letter\t ||\tAmount\n");
printf(" ================================\n");

    for(j = 0; alpha[j] != '\0'; j++)
    {
        count = 0;

        for (k = 0; sent[k]!= '\0'; k++)
        {

            if ( alpha[j] == sent[k])
            {                          
                count++;                                   
            }

        }

        printf("\t%c\t ||\t %u\n", alpha[j], count);
        printf(" --------------------------------\n");  
    }  


    return 0;

}

Every time I run this program I get the error "Segmentation Fault (Core Dumped)".每次我运行这个程序时,我都会收到错误“分段错误(核心转储)”。 However the program seems to run correctly.但是该程序似乎运行正常。 Why is this happening and what can I do to fix this?为什么会发生这种情况,我该怎么做才能解决这个问题?

In your code,在您的代码中,

 char sent[] = "\0"; 

is allocating the size of the array only equal to the size of the supplied initializer "\\0" (and null-terminator).分配的数组大小仅等于提供的初始值设定项"\\0" (和空终止符)的大小。 So, at a later point, by doing所以,稍后,通过做

fgets(sent, SIZE, stdin);

you're accessing out of bound memory.您正在访问越界内存。 This invokes undefined behavior .这会调用未定义的行为

To quote C11 standard, chapter §6.7.9引用C11标准,第 6.7.9 章

If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer.如果初始化了一个未知大小的数组,它的大小由具有显式初始化器的最大索引元素决定。 [...] [...]

What you need is to provide the array size at definition time like您需要的是在定义时提供数组大小,例如

 char sent[SIZE] = "\0"; 

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

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