【问题标题】:Segmentation fault in queue implementation with C使用 C 实现队列中的分段错误
【发布时间】:2013-04-22 19:57:47
【问题描述】:

我已经在 C 中实现了一个简单的队列系统。但是我遇到了函数 append 的问题。这不是每次都发生,只是几次,但我找不到共同点。

gdb 说分段错误是由while (*h){ 行引起的,但我认为没问题。

以下是函数:

int pop (int *h){
    int ret = *h, i;

    for (i = 0; i < 52; i++){
        if (!*(h+i)){
            *(h+i-1) = 0;
            break;
        }
        else{
            *(h+i-1) = *(h+i);
        }
    }   
    return ret;
}


void append(int *h, int i){
    while (*h){
        ++h;
    }   
    *h = i;
}

非常感谢。

注意:队列大小是固定的,因此进出队列的值的数量是固定的,因此问题不在于超出范围。

编辑

我已经解决了。以下是工作的功能:

int pop (int *h){
    int ret = *h, i;

    for (i = 1; i < 52; i++){
        if (!h[i]){
            h[i-1] = 0;
            break;
        }
        else{
            h[i-1] = h[i];
        }
    }   
    return ret;
}


void append(int *h, int i){
    int j;

    for (j = 0; j<52; j++){
        if (!h[j]) break;
    }   
    h[j] = i;
}

【问题讨论】:

  • 不是“关于越界”。 ?当i 为0 时,您引用的是*(h+i-1),即h[-1] ..
  • 展示如何初始化队列
  • 所以...你永远不能在队列中插入0 的值?!
  • while (*h) 循环如何停止?元素是 0 初始化的吗?

标签: c segmentation-fault queue implementation


【解决方案1】:

看在上帝的份上,请使用数组表示法 [] 而不是取消引用 *() 的指针。 在这里,您的代码具有正确的符号,问题出在哪里就很明显了。

int pop (int *h){
  int ret = *h, i;

  for (i = 0; i < 52; i++){    <--- Change to i=1
    if (!h[i]){                                                     
        h[i-1] = 0;        <------ Buffer underflow when h[0] == 0  
        break;                                                      
    }
    else{
        h[i-1] = h[i];     <------ Buffer underflow when h[0] != 0
    }
  }   
  return ret;
}   


void append(int *h, int i){   Where's the buffer overflow check ????
  while (*h){
    ++h;
  }   
  *h = i;
}

您是否还使用 0 值初始化了您的数组?此外,是否真的希望您的堆栈/队列不能包含 0 值?

编辑:这里是更正的版本

int pop (int *h)
{
  int ret = h[0], i = 1;
  do {
    h[i-1] = h[i];
  } while(h[i] && i<52);
  return ret;
}   


void append(int *h, int value)
{
int i;
  for(i=0; i<52; i++) {
    if(!h[i])
      break;
  }
  if(i<52)
    h[i] = value;
  else
    fprintf(stderr, "Array is full\n");
}

【讨论】:

  • 我已经用 0 个值初始化了我的数组,队列不能包含 0 个值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多