我有一个问题的问题,即在我的flex文件的定义部分中声明全局范围指针,然后在我的主体开始时 malloc
,但是一旦我的程序进入yylex()
,指针的值将设置为NULL
。
我一直都需要这个指针到struct
(这是struct Modele * model
),这基本上是指我从文件中存储所有结果的结构的指针,因此我实际上无法没有它,至少没有没有一个指向在main()
和yylex()
中都可以正常工作的结构的指针。
执行时,该程序陷入了segfault,试图在adress 0x4上写入;在Valgrind下运行该程序,并打印model
的值使我可以理解内存已正确分配,但是一旦调用了Yylex,model
的值是NULL
(打印(nil)
)。我在这里不使用任何标题,但是我尝试使用一个标题来存储我的所有结构,以及我的全局范围变量的声明,但没有成功。
我的问题是:面对这种行为我做错了什么?,通常没有这个问题的最好方法是什么?我不确定我是否曾经使用过全球范围的指针,所以可能是这个,或者是一个弹性的特定问题。...我有点迷路了!
这是我的代码的示例:
%{
#include <stdlib.h>
#include <stdio.h>
//some more includes and #defines
typedef struct Doc {
int classe;
uint32_t * words;
int current_index;
int current_size;
} doc;
typedef struct Modele {
int nb_classes;
int nb_docs;
int nb_docs_base;
int nb_docs_test;
int base_or_test;
int voc_size;
int M_test_size;
liste ** M_theta;
row_info * M_calc;
doc * M_test;
} modele;
//some more typedefs
modele * model; // <--- this is the pointer i talk about
//some more functions bodies .....
%}
couple_entiers [0-9]+:[0-9]+
// .......
%%
{couple_entiers} { model->nb_docs ++}
//.....
%%
int main (int argc, char ** argv)
{
// .....
modele * model = malloc(sizeof model); // <---- here is the malloc
model->nb_classes = 0;
model->nb_docs = 0;
model->nb_docs_base = 0;
model->nb_docs_test = 0;
model->voc_size = 0;
model->M_test = malloc (TAB_SIZE * sizeof(doc));
//....
if ((yyin = fopen(argv[1],"r")) == NULL){
printf("Impossible d'ouvrir %s !n",argv[1]);
exit(0);
}
yylex();
如果代码不足以抓住问题的来源,我将粘贴更多,我只想选择相关的部分。
我的问题是:面对这种行为我做错了什么?
您从未设置过文件范围变量。相反,您的main()
函数声明并初始化了同名和类型的 local 变量。本地声明"阴影"其范围内的文件范围。
要修复它,只需更改此问题...
modele * model = malloc(sizeof model);
...对此:
model = malloc(sizeof model);
如果您不使用类型的变量名称之前