0xE*_*D1E 0 c struct scanf segmentation-fault
我正在编写一个程序来计算信息熵,这是熵(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 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;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我输入第一个输入并点击输入它会产生分段错误.我使用了调试器,我发现为结构分配数据会导致分段错误.那是执行此代码行的时候
scanf("%s %f", chs[i].var, &chs[i].prob);
Run Code Online (Sandbox Code Playgroud)
发生了分段错误.
但我想不出这段代码中的错误.
为什么scanf()会出现分段错误?
chs[i].var是一个悬垂的指针.你必须先malloc记住它.
chs[i].var = malloc(Max_str_len + 1); //<--- this
scanf("%s %f", chs[i].var, &chs[i].prob);
Run Code Online (Sandbox Code Playgroud)