首页 > 解决方案 > 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)。我不知道是什么导致了这个问题,也不知道指针是如何给我这些的。

提前致谢,

米海

标签: cpointerssegmentation-fault

解决方案


*size++;

这可能是您的罪魁祸首-您没有更新size指向的值,而是更改size为指向不同的对象。Postfix++的优先级高于 unary *,因此表达式被解析为*(size++).

重写为

(*size)++;

看看这是否不会使问题消失。


推荐阅读