如何解决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;
当函数依赖全局变量时,这也是一个坏主意。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。