I am getting a segmentation fault with the following code after adding structs to my queue.
The segmentation fault occurs when the MAX_QUEUE is set high but when I set it low (100 or 200), the error doesn’t occur. It has been a while since I last programmed in C, so any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE 1000
struct myInfo {
char data[20];
};
struct myInfo* queue;
void push(struct myInfo);
int queue_head = 0;
int queue_size = 0;
int main(int argc, char *argv[])
{
queue = (struct myInfo*) malloc(sizeof(struct myInfo) * MAX_QUEUE);
struct myInfo info;
char buf[10];
strcpy(buf, "hello");
while (1)
{
strcpy(info.data, buf);
push(info);
}
}
void push(struct myInfo info) {
int next_index = sizeof(struct myInfo) * ((queue_size + queue_head) % MAX_QUEUE);
printf("Pushing %s to %d\n", info.data, next_index);
*(queue + (next_index)) = info;
queue_size++;
}
Output:
Pushing hello to 0
Pushing hello to 20
...
Pushing hello to 7540
Pushing hello to 7560
Pushing hello to 7580
Segmentation fault
I think your problem lies here:
You’re scaling
next_indexby the size of your structure but this is something done automatically by that second statement –*(queue + (next_index))is equivalent toqueue[next_index]and the latter is more readable to all but those of us who have been using C since K&R was first published 🙂In other words,
next_indexshould be a value from0toMAX_QUEUE-1, so try changing the first statement to remove the multiplication bysizeof(struct myInfo):And keep in mind that you’ll eventually overflow
queue_sizein that infinite loop of yours. You will presumably be checking to ensure thatqueue_sizeis not incremented beyond MAX_QUEUE in the final production-ready code, yes?