#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;
}
每次运行此程序时,我都会收到错误“段错误(核心转储)”。不过程序似乎运行正确。为什么会发生这种情况?我可以采取什么措施来解决这个问题?
最佳答案
在您的代码中,
char sent[] = "\0";
分配的数组大小仅等于所提供的初始值设定项“\0”
(和空终止符)的大小。所以,稍后,通过这样做
fgets(sent, SIZE, stdin);
您正在访问超出范围的内存。这会调用 undefined behavior .
引用 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. [...]
您需要的是在定义时提供数组大小,例如
char sent[SIZE] = "\0";
关于c - 带有数组的段错误(核心转储)C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901682/