簡體   English   中英

C中的指針和“非法指令(核心轉儲)”

[英]pointers & 'Illegal instruction (core dumped)' in C

我想寫一個語法分析器,但是當我運行代碼時,它給了我這個:

Illegal instruction (core dumped)

現在,我運行了調試器,它告訴我在第一次迭代時(所以它不能是上下文),錯誤發生在這里:

static int list(int poz, int *size) {
...
if(*size==poz)
...

這個函數是這樣調用的:

list(-1,&size);

這是執行操作的整個代碼:

static int nexttoken() {
  if(pointer==filesize)
    return -1;
  return cchar=file[++pointer];///file is an array where i keep the contents of the file (without spaces)
  
}
static void getint(int *atr) {
  *atr=0;
  while(isdigit(nexttoken()))
    *atr=(*atr)*10+cchar-'0';
  return;
}

///...

static int atom() {
  int integer,size,currentpoz;
  getint(&integer);
  while(cchar=='(') {
    currentpoz=pointer;
    list(-1,&size);
    integer%=size;
    pointer=currentpoz;
    integer=list(integer,&size);
    nexttoken();
  }
  return integer;
}
static int list(int poz,int *size) {
  *size=0;
  int retval=0;
  while(nexttoken()!=')') {
    if(*size==poz)
      retval=atom();
    else
      atom();
    *size++;
  }
  return retval;
}

我在另一個編譯器上運行了相同的代碼,它告訴我這是段錯誤(SIGSIEV)。 我不知道是什么導致了這個問題,或者一個指針是如何給我任何這些的。

提前致謝,

米海

*size++;

這可能是您的罪魁禍首 - 您沒有更新size指向的值,而是將size更改為指向不同的對象。 Postfix ++優先級高於一元* ,因此表達式被解析為*(size++)

將其改寫為

(*size)++;

看看這是否不會使問題消失。

對於初學者來說,這個函數看起來很可疑

static int nexttoken() {
  if(pointer==filesize)
    return -1;
  return cchar=file[++pointer];///file is an array where i keep the contents of the file (without spaces)
  
}

表達式++pointer可以等於filesize 這可以調用未定義的行為。

應該是cchar=file[pointer++]嗎?

相應地,函數list應該像

list( 0, &size);

代替

list(-1,&size);

在函數list這個表達式

*size++;

相當於

*( size++ );

那就是指針size指向的對象沒有被改變。

相反,你必須寫

++*size;

當函數依賴於全局變量時,這也是一個壞主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM