I have implemented a simple queue system in C. But I'm having problems with the function append. 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.
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;
}
iis 0, you are referencing*(h+i-1), which ish[-1]..0into your queue?!while (*h)loop expected to stop? Were elements 0-initialized?