c - 为什么这个 scanf 会导致段错误?

标签 c struct segmentation-fault scanf

我正在写一个计算信息熵的程序,这是熵(H)的函数

H(X) = -sigma(i = 1 to n){p(x_i)*log2(p(x_i)}

base 2 log is used here

然后这是我的程序

#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("%s %f", chs[i].var, &chs[i].prob);

发生段错误。

但我想不出这段代码有什么错误。

为什么这个 scanf() 会产生段错误?

最佳答案

chs[i].var 是一个悬挂指针。您必须先为它malloc 内存。

chs[i].var = malloc(Max_str_len + 1);  //<--- this
scanf("%s %f", chs[i].var, &chs[i].prob);

关于c - 为什么这个 scanf 会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34681323/

相关文章:

c - Malloc 段错误

c - 将指向结构的指针设置为等于函数返回的另一个指向结构的指针?

c - 我怎么知道为什么需要 libstdc++

c - 如何将 memmove 与指针的指针一起使用?

大型 mysqldump 段错误 --where=(id IN ...)

string - 使用分隔符打印结构体中的字段列表

c++ - 在 C++ 中对来自全局函数的结构成员使用方法

c++ - C++ 中的 Mat 和 Bmat

c - 我如何像UNIX中的Hexdump函数一样打印出地址

c++ - 使用 c/c++ 的文件 IO 技巧