在我的系统上运行您的代码时,我收到以下运行时错误:
230520-token(77235,0x20a1d8140) malloc: *** error for object 0x40000: pointer being freed was not allocated
230520-token(77235,0x20a1d8140) malloc: *** set a breakpoint in malloc_error_break to debug
/bin/sh: line 1: 77235 Abort trap: 6 ./230520-token
make: *** [230520-token.run] Error 134
阅读您的代码,我可以看到以下问题:
-
[专业]
也不
ctx
也没有
meta
在中初始化
main
。您应该初始化这些结构,以确保所有指针都为null:
Hx_File_Parsing_Context ctx = { 0 };
Hx_Compiler_Metadata meta = { 0 };
-
[专业]
在释放前一个令牌时,您应该测试它是否确实已分配:
if (ctx->prev_token) {
free(ctx->prev_token->value);
free(ctx->prev_token);
}
-
[专业]
在里面
init_string
,的初始值
string->length
应该是
0
。
-
append_char_to_string
不更改其第一个参数,则不需要更新
tok_val
像
tok_val = append_char_to_string(tok_val, ch);
,只需使用
append_char_to_string(tok_val, ch);
-
读取数字的循环应该只是
for (;;)
环使用
do
/
while
循环添加了冗余测试。不支持十六进制数字。
-
您应该将行号保存在
get_next_token
所以
line
字段设置为令牌开始的行。当您解析多行标记(如注释和带有转义换行符的多行中断标记)时,这将更加重要。
-
您应该解析标识符、运算符、字符串、字符常量、注释。。。
-
[专业]
你用释放绳子
free_string(tok_val);
但是您保存了指向令牌结构的内容指针,因此该指针无效。您应该分配一个字符串的副本
res->value = strdup(tok_val->data);
解决了上述主要问题,我得到了以下输出:
All Tokens in the file =
{ type: 6, value: 1, line: 1 },
{ type: 2, value: , line: 2 },
{ type: 7, value: 2.34, line: 2 },
{ type: 2, value: , line: 5 },
{ type: 1, value: x, line: 5 },
{ type: 1, value: x, line: 5 },
{ type: 1, value: y, line: 5 },
{ type: 2, value: , line: 5 },
{ type: 1, value: =, line: 5 },
{ type: 2, value: , line: 5 },
{ type: 8, value: 5e6, line: 5 },
{ type: 2, value: , line: 6 },
{ type: 0, value: , line: 6 },