C 为什么此扫描会导致分段错误?
我正在写一个程序来计算信息熵,这是熵(H)的函数 这里使用的是base 2 log 这是我的节目C 为什么此扫描会导致分段错误?,c,struct,segmentation-fault,scanf,C,Struct,Segmentation Fault,Scanf,我正在写一个程序来计算信息熵,这是熵(H)的函数 这里使用的是base 2 log 这是我的节目 #include <stdio.h> #include <math.h> #include <stdlib.h> #include <signal.h> typedef struct vars { char *var; float prob; } CHOISES; float infocont(float x); float en
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <signal.h>
typedef struct vars {
char *var;
float prob;
} CHOISES;
float infocont(float x);
float entropy(CHOISES *, int);
void onsig(int);
int main(int argc, char *argv[])
{
int i = 0;
int siz = 0;
float H = 0.0;
printf("input the number of vars: ");
scanf("%d", &siz);
//printf("echo: %d\n", siz);
CHOISES chs[siz];
signal(SIGSEGV, onsig);
for (i = 0; i < siz; i++) {
printf("%d: ", i + 1);
scanf("%s %f", chs[i].var, &chs[i].prob); /* HERE IS THE ERROR */
//printf("echo: %s %f\n", chs[i].var, chs[i].prob);
}
H = entropy(chs, siz);
printf("Entropy is %f\n", H);
}
void onsig(int signo)
{
fprintf(stderr, "signal caught: %d\nSEGMENTATION FAULT\n", signo);
}
float infocont(float x)
{
return (log(1/x) / log(2));
}
float entropy(CHOISES chs[], int len)
{
short i;
float entropy;
for (i = 0; i < len; i++) {
entropy += chs[i].prob * infocont(chs[i].prob);
}
return entropy;
}
出现分段错误
但我想不出这段代码中有什么错误
为什么这个scanf()会产生分段错误?
chs[i]。var
是一个悬空指针。您必须先为其malloc
内存
chs[i].var = malloc(Max_str_len + 1); //<--- this
scanf("%s %f", chs[i].var, &chs[i].prob);
chs[i].var=malloc(Max_str_len+1)//事实上,首先你必须在谷歌上搜索如何安全读取字符串的解决方案——你不知道它有多长。1个字符似乎不太多:-(@gnasher729:没有看到它是一个%smalloc
应该分配Max\u stru len+1
字节,而不仅仅是Max\u stru len
还需要检查是否!chs[i].var
是否为真
否则遵循scanf
可能会再次导致SegFault
。抓住了悬空指针-解决了当前问题。但是scanf(“%s…”
并不比get()
好多少。可以使用scanf(“%99s,
或更好的方法是替换所有scanf
使用fgets()
,但这将解决OP的下一个问题。谢谢,这“10”是本文的输入错误。在调试过程中使用了它。@0xEDD1E请检查更新的答案。它涵盖了另一个可能的SegFault
的机会,以备将来参考:同时发布输入的输入。
chs[i].var = malloc(Max_str_len + 1); //<--- this
scanf("%s %f", chs[i].var, &chs[i].prob);
for (i = 0; i < 10; i++)
{
printf("%d: ", i + 1);
scanf("%s %f", chs[i].var, &chs[i].prob); /* HERE IS THE ERROR */
//printf("echo: %s %f\n", chs[i].var, chs[i].prob);
}
for (i = 0; i < siz; i++)
{
printf("%d: ", i + 1);
chs[i].var = malloc((MAX_STRING_SIZE + 1)* sizeof(char));
if(!chs[i].var)
{
printf("Memory could not be allocated!\n");
exit(0);
}
scanf("%s %f", chs[i].var, &chs[i].prob);
printf("echo: %s %f\n", chs[i].var, chs[i].prob);
}