全面披露:这是我第一次在 C 中进行任何重要的编程,也是我在 Stack Overflow 上的第一篇文章。
我正在编写最终将与 Bison 一起使用的代码,以实现 Scheme/Racket 语言的一小部分。所有这些代码都在一个 C 文件中。我有三个结构:Binding
、Lambda
和SymbolEntry
。我还没有使用该Lambda
结构,它只是为了完整性。我还有一个包含符号条目的符号表。printSymbolTable()
完全符合名称的含义:
typedef struct
{
char* name;
char* value;
} Binding;
typedef struct
{
int numBindings;
Binding** bindings;
char* functionBody;
} Lambda;
typedef struct
{
Binding* binding;
Lambda* function;
} SymbolEntry;
SymbolEntry* symbolTable = NULL;
int numSymbols = 0;
void printSymbolTable()
{
if (symbolTable)
{
int i = 0;
for (i; i < numSymbols; i++)
{
printf("\tsymbolTable[%i]: %s = %s\n", i, symbolTable[i].binding->name, symbolTable[i].binding->value);
}
}
}
我目前正在尝试制定定义和查找变量的逻辑。2个相关功能:
// Takes a name and an exprssion and stores the result in the symbol table
void defineVar(char* name, char* expr)
{
printf("\nSetting %s = %s\n", name, expr);
printf("Previous number of symbols: %i\n", numSymbols);
Binding props;
props.name = name;
props.value = expr;
SymbolEntry entry;
entry.binding = &props;
entry.function = NULL;
symbolTable = realloc(symbolTable, sizeof(SymbolEntry) * ++numSymbols);
if (!symbolTable)
{
printf("Memory allocation failed. Exiting.\n");
exit(1);
}
symbolTable[numSymbols - 1] = entry;
printf("New number of symbols: %i\n", numSymbols);
printf("defineVar result:\n");
printSymbolTable();
}
// Test storing and looking up at least 4 variables, including one that is undefined
void testVars()
{
printf("Variable tests\n");
defineVar("foo", "0");
printf("After returning from defineVar:\n");
printSymbolTable();
defineVar("bar", "20");
printf("After returning from defineVar:\n");
printSymbolTable();
}
main()
来电testVars()
。编译时我没有收到任何警告或错误,并且程序成功执行。然而,结果如下:
Variable tests
Setting foo = 0
Previous number of symbols: 0
New number of symbols: 1
defineVar result:
symbolTable[0]: foo = 0
After returning from defineVar:
symbolTable[0]: 1�I��^H��H���PTI��@ = �E
Setting bar = 20
Previous number of symbols: 1
New number of symbols: 2
defineVar result:
symbolTable[0]: bar = 20
symbolTable[1]: bar = 20
After returning from defineVar:
symbolTable[0]: 1�I��^H��H���PTI��@ = �E
symbolTable[1]: 1�I��^H��H���PTI��@ = �E���
我不仅在defineVar()
函数之外得到垃圾值,而且对定义的调用也bar
显示了不正确的非垃圾值。我不确定我做错了什么,但我认为它可能与realloc()
. 但是,在将字符串解析为单个标记时,类似的策略会起作用,所以这就是我试图模仿的。我究竟做错了什么?