【发布时间】:2022-01-25 15:07:41
【问题描述】:
我的任务是创建一个编译器 我现在在这里列出了两个产生问题的函数。 下面我给出了它给出的输出 当我连续调用 cond3AC 函数时
s_3AC * e1 = cond3AC (tree-> childrens [0]);
我得到分段错误
如果您尝试跟踪打印,我会正确分配并正确返回所有内容。
s_3AC* Exp3AC(node *tree){
if(!strcmp("&&", tree->token) || !strcmp("||", tree->token) || !strcmp("==", tree->token) || !strcmp("!=", tree->token)||
!strcmp(">", tree->token) || !strcmp(">=", tree->token) || !strcmp("<", tree->token) || !strcmp("<=", tree->token)){
red();
printf("######## check now the e2 ########## \n");
printf("check token right: %s\n",tree->childrens[1]->token);
s_3AC* e2 = cond3AC(tree->childrens[1]);
printf("e2 -> %s\n", e2->code);
purple();
printf("######## check now the e1 ########## %s\n", tree->childrens[0]->token);
printf("check token left: %s\n",tree->childrens[0]->token);
/* send left side to evaluate*/
s_3AC* e1 = cond3AC(tree->childrens[0]);
printf("e1 -> %s", e1->code);
reset();
s_3AC* node = (s_3AC*)malloc(sizeof(s_3AC) * 1);
node->code = (char*)malloc(sizeof(char) * (strlen(tree->token) + strlen(e1->code) + strlen(e2->code) + 1));
strcat(node->code,e1->code);
strcat(node->code,tree->token);
strcat(node->code,e2->code);
node->var = NULL;
node->falsel = NULL;
node->truel = NULL;
return node;
}else{
s_3AC* node = (s_3AC*)malloc(sizeof(s_3AC));
printf("SUCCESS\n");
node->code = strdup(tree->token);
node->var = strdup(tree->token);
node->truel = NULL;
node->falsel = NULL;
return node;
}
s_3AC* cond3AC(node *tree){ printf("OKOKOK\n"); printf("tree->token: %s\n",tree->token); if(is_kind_of_type(tree->token)){ char *code = (char*)malloc(sizeof(char) * (strlen(tree->childrens[0]->token) + 1)); printf("tree->token after the if: %s\n",tree->token); strcat(code, tree->childrens[0]->token); s_3AC* node = (s_3AC*)malloc(sizeof(s_3AC) * 1); node->code = strdup(code); node->var = NULL; node->truel = NULL; node->falsel = NULL; return node; } s_3AC* check = Exp3AC(tree); printf("ˆˆˆˆcheck->codeˆˆˆˆ: %s\n", check->code); return check; }
输出:
######## check now the e2 ##########
check token right: int
OKOKOK
tree->token: int
tree->token after the if: int
e2 -> 23
######## check now the e1 ########## a
check token left: a
OKOKOK
tree->token: a
SUCCESS
ˆˆˆˆcheck->codeˆˆˆˆ: a
zsh: segmentation fault ./Part3 < test.t
【问题讨论】:
-
@WeatherVane 我不明白这有什么关系?当他试图为 e1 放置位置时,他甚至在到达那里之前就摔倒了,他已经摔倒了 "s_3AC* e1 = cond3AC(tree->childrens[0]);"
-
我将评论移至答案,因为这是代码错误。也许有类似的错误,或者您将
NULL指针传递给字符串函数或未终止的字符串。错误可能出现在代码中的任何地方:内存损坏并不总是会立即导致错误。
标签: c memory segmentation-fault malloc