【发布时间】:2016-03-17 08:37:50
【问题描述】:
我正在尝试使用 Jack Crenshaw 的教程 http://compilers.iecc.com/crenshaw/ 在 C(Ubuntu,gcc)中编写编译器程序。 但是,它是用 Pascal 编写的,而且我对 C 语言比较陌生,所以我尽可能地编写了一个。
我需要一些帮助。发生分段错误。查看 Valgrind 的输出:
==3525== Invalid read of size 1
==3525== at 0x80484C0: GetChar (in /home/spandan/codes/Compiler_1)
==3525== by 0x8048AAD: Init (in /home/spandan/codes/Compiler_1)
==3525== by 0x8048ACD: main (in /home/spandan/codes/Compiler_1)
==3525== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3525==
==3525==
==3525== Process terminating with default action of signal 11 (SIGSEGV)
==3525== Access not within mapped region at address 0x0
==3525== at 0x80484C0: GetChar (in /home/spandan/codes/Compiler_1)
==3525== by 0x8048AAD: Init (in /home/spandan/codes/Compiler_1)
==3525== by 0x8048ACD: main (in /home/spandan/codes/Compiler_1)
我将在此处发布与 Valgrind 的堆栈跟踪相关的部分代码。其余的可以在:http://pastebin.com/KBHyRC1n 找到。
请帮忙解释一下。根据我的说法,所有指针都正确使用。我想为这个程序提供命令行输入,但即使我不这样做,它仍然会出现段错误。
#include<stdio.h>
#include<stdlib.h>
static char *Look;
static int LookP = 0;
//read new character from input stream
char GetChar(){
char x;
x= Look[LookP];
LookP++;
return x;
}
// initializer function
void Init(char *c){
Look=c;
GetChar();
//SkipWhite();
}
int main(int argc, char *argv){
Init(argv[1]);
//Assignment();
if (Look[LookP] != '\r'){
// Expected('Newline');
}
return 0;
}
【问题讨论】:
-
您应该收到关于调用
Init的编译器警告。它期望char *但argv[1]只是char。 -
您还应该告诉我们您是如何调用程序的,尤其是命令行参数是什么。
-
@MichaelWalz 我什至没有时间输入命令行参数。在windows中,弹出控制台在我可以之前关闭,在linux中,没关系,我给或不给任何参数,它说“分段错误,核心转储”。
-
@Barmar:令人惊讶的是,我没有收到来自
Init的警告。但是,如果您从我提供的链接中看到我的整个程序,我会在整个程序中收到很多warning: makes pointer from integer without a cast。但是,它似乎肯定会卡在GetChar()。可能是什么问题? -
@Spandan 最好从实际命令行运行程序以使用命令行参数。遵循 MikeCAT 在his answer to your question 中的建议也应该至少解决了您的一些问题。
标签: c compiler-construction segmentation-fault