简体   繁体   English

用C实现队列中的分段错误

[英]Segmentation fault in queue implementation with C

I have implemented a simple queue system in C. But I'm having problems with the function append. 我已经在C语言中实现了一个简单的队列系统。但是我在函数追加方面遇到了问题。 This doesn't happen every time, just a few times, but I cannot find the common denominator. 这并非每次都发生,只是几次,但是我找不到共同点。

gdb says the segmentation fault is caused by the line while (*h){ but I think it is OK. gdb表示分段错误是由while (*h){引起的,但我认为这是可以的。

Here are the functions: 功能如下:

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;
}

Thank you very much. 非常感谢你。

A note: the queue size is fixed, and so the number of values that go into and out of it, so the problem isn't about going out of bounds. 注意:队列大小是固定的,因此进入和离开队列的值的数量是固定的,因此问题不在于越界。

EDIT 编辑

I have fixed it. 我已经解决了。 Here are the functions working: 以下是起作用的功能:

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;
}

For gods sake, use the array notation [] instead of the pointer dereferencing *() . 出于上帝的缘故,请使用数组符号[]而不是将指针取消引用*()的指针。 Here your code with the right notation and it gets obvious where the problem is. 在这里,您的代码带有正确的符号,并且可以清楚地看出问题出在哪里。

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;
}

Have you also initialized your array with 0 values? 您是否还使用0值初始化了数组? Furthermore, is it really wanted that your stack/queue can not contain a 0 value? 此外,是否真的希望您的堆栈/队列不能包含0值?

EDIT: Here the corrected version 编辑:这里更正的版本

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM