c - 为什么我在访问整数数组时会立即出现段错误?
问题描述
我发送初始化代码数组的大小为 500,然后用整数填充它并将其发送到此函数以使用数组值填充结构。但是当尝试访问 code[0] 时,机器崩溃了。
instruction *fetchCycle(int *code, instruction *ir, int pc)
{
int index = pc * 4;
printf("accessing code[%d]\n", index);
ir->op = code[index++];
printf("accessing code[%d]\n", index);
ir->r = code[index++];
printf("accessing code[%d]\n", index);
ir->l = code[index++];
printf("accessing code[%d]\n", index);
ir->m = code[index++];
printf("accessing code[%d]\n", index);
return ir;
}
这是调用 fetchCycle() 的函数
// takes in a single instruction and executes the command of that instruction
void executionCycle(int *code)
{
int l, m, sp = MAX_DATA_STACK_HEIGHT, bp = 0, pc = 0, gp = -1, halt = 0, i = 0;
int data_stack[41] = {0}, reg[200];
instruction *ir;
// Capturing instruction integers indicated by program counter
ir = fetchCycle(code, ir, pc++);
// printf("5\n");
while (halt == 0)
{
// printf("6\n");
switch(ir->op)
{ ...
这是终端的输出:
访问代码[0] 分段错误(核心转储)
解决方案
代码片段:
instruction *ir;
// Capturing instruction integers indicated by program counter
ir = fetchCycle(code, ir, pc++);
有问题,您传递给函数的是一个未初始化的指针ir
,因此当函数尝试访问它的成员时它不能,因为它们不存在。
至于code
我不能说,因为它是函数的参数executionCycle
,我不知道它指向哪里。您可能也应该在问题中包含该函数的调用者。
推荐阅读
- jira - JIRA - 当原始问题进度更改时自动更改克隆问题的进度
- c - 联合指针
- elasticsearch - 我们可以使用弹性搜索来获得一致的结果吗?
- rdf - 是否有任何关于 AIML-OWL 集成的实施指南?
- javascript - 浮动图表条间距
- java - 如何在 Spring Boot 中为控制器编写单元测试
- ios - UISlider 子类不会超出 0 - 1 范围
- google-apps-script - 如何让脚本在所有带有复选框的行中运行,但让它在指定的行上做一些稍微不同的事情?
- html - CSS 关键帧(动画)在 Safari 中不起作用
- java - 有没有其他方法可以从数组中提取元素对?