首页 > 解决方案 > 为什么我在访问整数数组时会立即出现段错误?

问题描述

我发送初始化代码数组的大小为 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] 分段错误(核心转储)

标签: carrayspointerssegmentation-faultinteger

解决方案


代码片段:

instruction *ir;

// Capturing instruction integers indicated by program counter
ir = fetchCycle(code, ir, pc++);

有问题,您传递给函数的是一个未初始化的指针ir,因此当函数尝试访问它的成员时它不能,因为它们不存在。

至于code我不能说,因为它是函数的参数executionCycle,我不知道它指向哪里。您可能也应该在问题中包含该函数的调用者。


推荐阅读