c-我有分段错误,我不明白的方式



我有一项任务要创建一个编译器我现在已经在这里列出了产生问题的两个函数。下面我给出了它的打印输出当我调用一行中的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: %sn",tree->childrens[1]->token);
s_3AC* e2 = cond3AC(tree->childrens[1]);
printf("e2 -> %sn", e2->code);
purple();
printf("######## check now the e1 ########## %sn", tree->childrens[0]->token);
printf("check token left: %sn",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("SUCCESSn");
node->code = strdup(tree->token);
node->var = strdup(tree->token);
node->truel = NULL;
node->falsel = NULL;
return node;
}
s_3AC* cond3AC(node *tree){
printf("OKOKOKn");
printf("tree->token: %sn",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: %sn",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ˆˆˆˆ: %sn", 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

考虑以下代码行:

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);

分配的内存尚未初始化,第一个strcat希望有一个有效的C字符串(空字符串(。函数将在内存中搜寻,直到找到一个字符串终止符来开始追加,该终止符可能在内存分配之外。

将第一个strcat更改为strcpy,以便

node->code = (char*)malloc(sizeof(char) * (strlen(tree->token) + strlen(e1->code) + strlen(e2->code) + 1));
strcpy(node->code,e1->code);
strcat(node->code,tree->token);
strcat(node->code,e2->code);

相关内容

  • 没有找到相关文章

最新更新