2016-03-17 66 views
-2

我想用C(Ubuntu,gcc)编写一个使用Jack Crenshaw的教程http://compilers.iecc.com/crenshaw/的编译器程序。然而,它是用Pascal编写的,我对C相对比较陌生,所以我试着尽我所能编写一个。C - 程序抛出的分段错误

我需要一些帮助。 A 分段错误正在发生。请参阅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; 
} 
+0

你应该得到一个编译器警告有关调用'Init'。它期望'char *',但'argv [1]'只是'char'。 – Barmar

+1

您还应该告诉我们如何调用您的程序,特别是命令行参数。 –

+0

@MichaelWalz我甚至没有时间输入命令行参数。在windows中,弹出式控制台在我可以关闭之前关闭,在linux中,无关紧要,我给出或没有任何参数,它说“分段错误,核心转储”。 – Spandan

回答

3

main()的签名是错误的。它应该是int main(int argc, char **argv){(在argv之前再添加一个*

也应该在使用它们之前检查命令行参数的数量。

+0

我甚至没有时间输入命令行参数。在Windows中,弹出式控制台在我可以关闭之前关闭,在Linux中,这并不重要,我给出或没有任何参数,它说'分段故障,核心转储'。另外,我按照你说的main()方法做了,但是它没有帮助。你认为分段故障的原因是什么?我在GetChar()中做错了什么? – Spandan

0

有许多问题:

  • SkipWhite没有定义
  • main签名是错误的,应该是int main(int argc, char **argv)
  • Assignment没有定义
  • Expected没有定义
  • Expected('Newline');不做敏感,你的意思是Expected("Newline");
  • argv[1]如果没有命令行参数且程序很可能会崩溃,则为NULL。

要从IDE运行程序时指定命令行参数,请使用相应的选项(在Visual Studio 2015中,右键单击解决方案资源管理器中的项目,选择Debugging并在“Commande”参数“,对于其他我不知道的IDE)。

你应该检查的命令行参数的数量是错误的,e.g:

int main(int argc, char **argv){ 
    if (argc < 2) 
    { 
    printf("argument missing\n"); 
    return 1; 
    } 
    ... 
}