尝试将int传递到指针时发生总线错误
我正在尝试构建一个简单的程序集模拟器。 我想创建设置功能;该函数将采用2个参数(字符串数组)arg1 & arg2。 然后它将比较字符串与字符串数组,这是函数指针数组列表的索引。尝试将int传递到指针时发生总线错误
我遇到的问题是当我尝试设置寄存器的值。 我已经尝试了很多变种的线路:
*register_ptr[i] = *(int*)(atoi(arg2));
没有成功;有什么我不明白的吗?
该代码将希望得到更清晰:
int opcode_set(char* opcode, char *arg1, char *arg2)
{
int i, j;
//printf("%d\n", (int)arg2);
for(i=0;i<4;i++)
{
if(!strcmp(arg1, register_str[i]))
{
for(j=0;j<4;j++)
{
if(!strcmp(arg2, register_str[i]))
{
*register_ptr[i] = *(int*)register_ptr[j];
}
else
{
*register_ptr[i] = *(int*)(atoi(arg2));
}
}
}
}
//printf("%d", *register_ptr[i]);
INSP++; /* NOP does not do anything except moving the instruction pointer to the next instruction */
return (0);
}
编辑: 声明为register_str & register_ptr:
const char *register_str[] = {"REGA", "REGB", "REGC", "REGX"};
int *register_ptr[]={®A, ®B, ®C, ®X};
我使用两个阵列以决定哪些操作码,一个字符串数组,和一个函数指针数组,我通过字符串索引并使用相同的索引位置来调用函数:
int exec_instruction(char *instruction){
int i; //used for indexing
/* the line below may be useful for debugging to see the current instruction*/
/*printf("executing line: %s", instruction);*/
/* three variables could be used to extract opcode and
arguments from the variable instruction */
char *opcode = NULL;
char *arg1 = NULL;
char *arg2 = NULL ;
char *copy = NULL;
/* we need here some functionality to extract opcode,
arg1 and arg2 from the string instruction*/
copy = strdup(instruction);
opcode = strtok(copy," \n\r");
arg1 = strtok(NULL," \n\r");
arg2 = strtok(NULL," \n\r");
/* Now we have to call the right function corresponding
to the right opcode For example: */
for(i = 0; i < 10; i++)
{
if(!strcmp(opcode_str[i], opcode))
(*opcode_func[i])(opcode,arg1,arg2);
}
/* for demonstration purpose we execute NOP independent of input
this line must go in your implementation */
(*opcode_func[0])("NOP",NULL,NULL);
/* return value should be 0 if execution was ok otherwise -1*/
return(0);
}
两个数组我谈到:
const char *opcode_str[] = {"NOP", "SET", "AND", "OR", "ADD", "SUB", "SHL", "SHR", "JMP", "PRT"};
opcode_function opcode_func[] = { &opcode_nop, &opcode_set, &opcode_and, &opcode_or, &opcode_add, &opcode_sub, &opcode_shl, &opcode_shr, &opcode_jmp, &opcode_prt };
鉴于声明register_ptr
,该行:
*register_ptr[i] = *(int*)register_ptr[j];
}
else
{
*register_ptr[i] = *(int*)(atoi(arg2));
都是错误的(一个无害,少了一个无害)。第一个不需要演员;你可以非常清楚写:
*register_ptr[i] = *register_ptr[j];
第二真的不需要任何铸造要么,但它并不需要间接的级别之一:
*register_ptr[i] = atoi(arg2);
这种分配由atoi(arg2)
返回的整数到register_ptr[i]
指向的内存,推测可能是REGA
,REGB
,REGC
或REGX
之一。正如你写的,你正在将arg2
中的值视为模拟器内存空间中的地址,并读取那里的值,以及各种(可能)不需要的后果(例如核心转储)。
我仍然得到核心转储时,我改变了行,感谢您的帮助,虽然, 我已经尝试过这之前来一个相同的问题 – Babbleshack 2013-05-08 23:32:31
你会得到来自核心转储的相同堆栈跟踪?如果是这样,它可能不是指向那些线。 – 2013-05-08 23:38:58
嗯,我相信已经工作实际上,因为现在我没有输出,这可能意味着我做了别的事情不对 – Babbleshack 2013-05-08 23:40:25
arg2究竟是什么?这是一个有效的内存地址来读取一个int? – 2013-05-08 23:06:59
你确定你不是指'register_ptr [i] =(int *)(atoi(arg2));'? – 2013-05-08 23:08:38
arg2将是一个字符串,具有常数(数字)或寄存器(REGA,REGB,REGC,REGX)。我不明白你的意思你的第二个问题 – Babbleshack 2013-05-08 23:09:42