C 中的指针 & 'Illegal instruction (core dumped)'

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 以指向不同的对象。后缀 ++ 的优先级高于一元 *,因此该表达式被解析为 *(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;

当函数依赖于全局变量时也是一个坏主意。