Home > OS >  Segmentation fault when attempting enqueue
Segmentation fault when attempting enqueue

Time:12-30

I have a simple function that should perform enqueuing based on the following algorithm:

Algorithm: ENQUEUE (Q, ITEM)
[Q is an array represent queue and ITEM is deleted item]
1. [check overflow]
If Rear = MAX - 1 then
a) Print: Queue is Full
b) Return
2. Set Rear = Rear   1
3. Q[Rear] = ITEM
4. Return

I have attempted two approaches and one provides me with a segmentation fault error, and I cannot understand why.

Here is the working implementation:

#define MAXSIZE 255
typedef struct Stack {
    int Q[MAXSIZE]; 
    int rear;
} Stack_t;

int enqueue(int item,int(*Q)[item] ){
    int rear;
    if (rear == sizeof(*Q)/sizeof((*Q)[0])-1){
        printf("Queue is Full!");
        return -1;
    }
    rear  ;
    (*Q)[rear] = item;
    return rear;
}

int main(void){
    Stack_t s = {.rear = -1};
    int arr[10] = {0, 1, 2, 3, 4, 5};
    int item = 2;
    int result;
    result = enqueue(item, &arr);
    printf("\nResult: {%i}", arr[result]);
    return 0;
}

This will print out:

Queue is Full!
Result: {0}%  

Whereas, the original implementation I had in mind would not work, it goes likeso:

int enqueue(int(*Q)[], int item, int size){
    int rear;
    if (rear == size-1){
        printf("Queue is Full!");
        return -1;
    }
    rear  ;
    (*Q)[rear] = item;
    return rear;
}

int main(void){
    Stack_t s = {.rear = -1};
    Stack_t q = {.Q = {0, 1, 2, 3, 4, 5}};
    int arr[10] = {0, 1, 2, 3, 4, 5};
    int item = 2;
    int result;
    int size = sizeof(q.Q)/sizeof(q.Q[0]);
    result = enqueue(&q.Q, item, size);
    printf("\nResult: {%i}", q.Q[result]);
    return 0;
}

I am new to indexing structs and recently learnt them from my latest question (before this one.) So perhaps q.Q is not the exact expression, otherwise, the size is not properly captured.

CodePudding user response:

Use the array in the struct to store the enqueued integers.
Pass a pointer to the structure to the function.

#include <stdio.h>

#define MAXSIZE 255

typedef struct Stack {
    int Q[MAXSIZE];
    int rear;
} Stack_t;

int enqueue ( int item, Stack_t *q){
    int max = ( sizeof q->Q / sizeof q->Q[0]) - 1;
    if ( q->rear == max) {
        printf ( "Queue is Full!\n");
        return q->rear;
    }
    q->rear  ;
    q->Q[q->rear] = item;
    return q->rear;
}

int main ( void) {
    Stack_t s = {.rear = -1};
    int item = 2;
    int result;
    result = enqueue ( item, &s);
    printf ( "Result: {%i}\n", s.Q[result]);
    item = 12;
    result = enqueue ( item, &s);
    printf ( "Result: {%i}\n", s.Q[result]);
    return 0;
}
  •  Tags:  
  • c
  • Related