带数组的段错误(核心转储)C 程序
Segmentation Fault (Core Dumped) C Program with Arrays
#include <stdio.h>
#include <string.h>
#define SIZE 1000
int main(void)
{
char sent[] = "[=10=]";
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] != '[=10=]'; j++)
{
count = 0;
for (k = 0; sent[k]!= '[=10=]'; k++)
{
if ( alpha[j] == sent[k])
{
count++;
}
}
printf("\t%c\t ||\t %u\n", alpha[j], count);
printf(" --------------------------------\n");
}
return 0;
}
每次我 运行 这个程序我都会得到错误 "Segmentation Fault (Core Dumped)"。但是该程序似乎 运行 正确。为什么会发生这种情况,我该怎么做才能解决这个问题?
在您的代码中,
char sent[] = "[=10=]";
分配的数组大小仅等于提供的初始值设定项 "[=13=]"
(和空终止符)的大小。所以,稍后,通过做
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] = "[=12=]";
#include <stdio.h>
#include <string.h>
#define SIZE 1000
int main(void)
{
char sent[] = "[=10=]";
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] != '[=10=]'; j++)
{
count = 0;
for (k = 0; sent[k]!= '[=10=]'; k++)
{
if ( alpha[j] == sent[k])
{
count++;
}
}
printf("\t%c\t ||\t %u\n", alpha[j], count);
printf(" --------------------------------\n");
}
return 0;
}
每次我 运行 这个程序我都会得到错误 "Segmentation Fault (Core Dumped)"。但是该程序似乎 运行 正确。为什么会发生这种情况,我该怎么做才能解决这个问题?
在您的代码中,
char sent[] = "[=10=]";
分配的数组大小仅等于提供的初始值设定项 "[=13=]"
(和空终止符)的大小。所以,稍后,通过做
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] = "[=12=]";