2016-03-17 89 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; 
    } 
    ... 
}