【发布时间】:2018-05-15 01:09:57
【问题描述】:
我目前正在使用 C++ 创建一个小型编译器。我定义了以下对象:
struct ValueNode
{
std::string name;
int value;
};
struct StatementNode
{
StatementType type;
union
{
struct AssignmentStatement * assign_stmt;
struct PrintStatement * print_stmt;
struct IfStatement * if_stmt;
struct GotoStatement * goto_stmt;
};
struct StatementNode * next; // next statement in the list or NULL
};
我已经定义了一系列与语言中不同类型的语句相关的函数。这些函数之一称为 parse_assignment_stmt()。我遇到的分段错误发生在此函数中,在尝试为最近分配的内存分配值后立即发生。这是那个函数:
struct StatementNode* parse_assign_stmt() {
//Object to be returned. Holds an object representing a statement
//made within the input program.
struct StatementNode* st = (struct StatementNode*)malloc(sizeof(struct StatementNode));
st->type = ASSIGN_STMT;
//First token should be an ID. Represents memory location we are assigning to.
Token tok = lexer->GetToken();
if(tok.token_type == ID) {
//Second token in an assignment should be an equal sign
Token tok2 = lexer->GetToken();
if (tok2.token_type == EQUAL) {
//This function reads the next token, makes sure it is of type NUM or ID, then creates and returns a ValueNode containing the relevant value.
struct ValueNode* rhs1 = parse_primary();
Token tok3 = lexer->GetToken();
//Assignment format for this logical branch: "x = 5;"
if(tok3.token_type == SEMICOLON) {
//first type
//Allocate memory for objects needed to build StatementNode st
struct AssignmentStatement* assign_stmt = (struct AssignmentStatement*)malloc(sizeof(struct AssignmentStatement));
struct ValueNode* lhs = (struct ValueNode*)malloc( sizeof(struct ValueNode));
printf("Name: %s, Value: %d\n", lhs->name.c_str(), lhs->value);
//PROBLEM ARISES HERE***
//lhs->name = tok.lexeme;
//return the proper structure
return st;
}
else if(tok3.token_type == PLUS || tok3.token_type == MINUS || tok3.token_type == DIV || tok3.token_type == MULT) {
//second type
//TODO
}
else {
printf("Syntax error. Semicolon or operator expected after first primary on RHS of assignment.");
exit(1);
}
}
else {
//not of proper form
printf("Syntax error. EQUAL expected after LHS of assignment.");
exit(1);
}
}
else {
//Not of proper form. Syntax error
printf("Syntax error. ID expected at beginning of assignment.");
exit(1);
}
}
本质上,我正在为新的 ValueNode 分配内存以创建变量 lhs。我立即打印出名称和值字段,以确保不存在任何内容。在我的编译器输出中(顺便说一下,我使用的是 g++),它告诉我名称为 (null),值为 0,这是预期的。一旦我取消注释该行
lhs->name = tok.lexeme;
我遇到了分段错误。在这一点上,我不知道出了什么问题。我正在创建变量,使用 malloc 为该位置分配内存,确保那里没有存储任何东西,然后立即尝试写入一个值。它总是给我一个分段错误。
这是通过标准输入输入程序的输入程序(.txt 文件)。
i;
{
i = 42 ;
print i;
}
我尝试使用 calloc() 代替,因为这应该确保在返回指针之前清除内存,但这并没有改变任何东西。任何建议都会很棒。谢谢!
【问题讨论】:
-
不要在 c++ 代码中使用
malloc()。 -
您可能需要考虑用适当的继承层次结构替换联合的
struct。那么你就不会被认为是一个 C+ 程序员,那种从未完全从 C 过渡到 C++ 的奇怪品种 :-) -
This question 还为您提供了一些提示,在 c++ 中的大多数情况下,如何以及为什么要完全放弃 手动动态内存分配。
标签: c++ pointers memory memory-management