【问题标题】:C - program throwing segmentation fault [closed]C - 程序抛出分段错误[关闭]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我什至没有时间输入命令行参数。在windows中,弹出控制台在我可以之前关闭,在linux中,没关系,我给或不给任何参数,它说segmentation fault, core dumped。另外,我按照你对main() 说的做了,但是没有帮助。您认为分段错误的原因是什么?我在GetChar() 做错了吗?
【解决方案2】:

有很多问题:

  • 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;
  }
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多