我即将对此分段错误感到厌烦。我正在写一个简单的2通汇编器。剥离中间文件以获得操作码,符号表条目等工作正常。现在我正在将机器代码缓冲区打印到控制台,但是有些问题导致了分段错误。使用cout进行打印时出现分段错误
#include"./assembler.h"
using namespace std;
int main(void)
{
ifstream inf("pooltab");
int pooltab[10],pooltab_ptr=0;
while(true)
{
int x;
inf>>x;
if(inf.eof()) break;
pooltab[pooltab_ptr++] = x;
}
for(int i=0;i<pooltab_ptr;i++)
cout<<pooltab[i]<<endl;
pooltab_ptr = 0;
inf.close();
inf.open("intermediate.asm");
// ofstream outf("machine_code");
sym_tab symtab;
literal_tab littab;
symtab.create_tab();
littab.create_tab();
char buf[50],*token,*m_code_buf,ch;
int loc_cntr=0,id,ltrl,a,b;
while(true)
{
inf.getline(buf,50);
if(inf.eof()) break;
token = strtok(buf,"(), ");
if(token != NULL)
{
if(token[0] == 'A' && token[1] == 'D')
{
token = strtok(NULL,",)");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
id = atoi(token);
if(id == 1 || id == 2)
{
token = strtok(NULL,",() C");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
loc_cntr = atoi(token);
}
}
if(token[0] == 'I' && token[1] == 'S')
{
token = strtok(NULL,",)");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
id = atoi(token);
if(id == 10 || id == 11)
{
token = strtok(NULL,"S,() ");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
a = atoi(token);
a = symtab.get_addr(a);
sprintf(m_code_buf,"%03d) + %02d 0 %03d\n",loc_cntr,id,a);
cout<<m_code_buf;
}
else if(id == 1)
{
sprintf(m_code_buf,"%03d) + %02d 0 000\n",loc_cntr,id);
printf("%s",m_code_buf);
}
else if(id > 1 || id < 10)
{
token = strtok(NULL,"() ");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
a = token[0] - 48;
token = strtok(NULL," (,");
if(token == NULL)
{
cerr<<"null token error";
return -1;
}
ch = token[0];
printf("%d %d %c \n",id,a,ch);
}
loc_cntr++;
}
}
}
inf.close();
// outf.close();
return 0;
}
这是我检查在中间代码文件命令语句(IS,1) (1) (S,1)
的方式。错误在sprintf
。现在,当我修改代码时,故障似乎从一个地方跳到另一个地方。例如,在一次我使用cout
而不是printf
。然后sprintf
就好了,但是cout产生了错误。那么我改变了生成pooltab的方式,现在sprintf
是麻烦制造者。
您可能在某处导致未定义的行为。向我们展示完整的功能(以及令牌的定义)。 – 2013-03-10 12:55:13
实际代码太大,但尚未完成,但确定。 – Ajinkya 2013-03-10 13:01:41
char m_code_buf [256];做了一个简单的改变。非常感谢你们。 – Ajinkya 2013-03-10 13:28:52