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