【问题标题】:Why do I immediately segfault when accessing an integer array?为什么我在访问整数数组时会立即出现段错误?
【发布时间】:2020-05-17 15:05:23
【问题描述】:

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

【问题讨论】:

  • 指令可能不是整数。您应该使用unsigned char 将它们作为内存中的字节访问。
  • 请提供A Minimal, Complete, and Verifiable Example (MCVE)code 在哪里声明和初始化?它只是一个未初始化的指针吗?还是指针已经超出了它指向的末尾? -- 这肯定可以解释 SegFault。

标签: c arrays pointers segmentation-fault integer


【解决方案1】:

代码片段:

instruction *ir;

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

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

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

【讨论】:

  • 很高兴你解决了问题,如果答案解决了问题别忘了accept the answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多