C - 程序抛出分段错误

时间:2016-03-17 08:37:50

标签: c compiler-construction segmentation-fault

我正在尝试使用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找到。

请帮忙解释一下。据我所知,所有指针都正确使用。我想为这个程序提供命令行输入,但即使我不知道,它仍然是segfaulting。

#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;
}

2 个答案:

答案 0 :(得分:3)

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

此外,您应该在使用它们之前检查命令行参数的数量。

答案 1 :(得分:0)

有很多问题:

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

要在IDE中运行程序时指定命令行参数,请使用相应的选项(在Visual Studio 2015中右键单击解决方案资源管理器中的项目,选择“调试”并在“Commande Arguments”下放置您想要的任何内容,对于我不知道的其他IDE。

您应该检查命令行参数的数量是否错误,例如:

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