Разбираюсь с синхронизацией потоков, в роли функции для второго потока является получение элементов очереди (queue).
Столкнулся с возникновением ошибки сегментирования, при выводе элементов очереди в потоке. Если выводить элементов ~1000, ошибки сегментирования не возникает, при выводе например 2500 элементов возникает ошибка и сигнал SIGSEGV убивает процесс. я подразумеваю что ошибка в функции get_queue и программа лезет в чужую область памяти.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#define COUNT 2500
typedef struct queue_s {
const char* data;
struct queue_s* next;
} queue_t;
queue_t* init_queue(const char* str)
{
queue_t* queue = (queue_t*) malloc(sizeof(queue_t));
char* data = (char*) malloc(strlen(str));
queue->next = NULL;
strcpy(data, str);
queue->data = data;
return queue;
}
void add_queue(queue_t* queue, const char* str)
{
while (queue->next != NULL)
queue = queue->next;
queue->next = init_queue(str);
}
queue_t* get_queue(queue_t* queue)
{
const char* data = queue->data;
printf("data = %s\n", data);
return queue->next;
}
void thread_cycle(queue_t* queue)
{
int i;
for (i = 0; i < COUNT; i++)
{
queue = get_queue(queue);
}
}
void *thread_func (void* arg)
{
printf("Thread worked\n");
queue_t* queue = (queue_t*) arg;
thread_cycle(queue);
return NULL;
}
void main_cycle(queue_t* queue)
{
int i;
char str[10];
for (i = 0; i < COUNT; i++)
{
sprintf(str, "Q%d", i+1);
add_queue(queue, str);
}
}
int main (int argc, char *argv[])
{
printf("Main worked\n");
pthread_t thread;
queue_t* queue = init_queue("QInit");
if (pthread_create(&thread, NULL, thread_func, queue) != 0)
{
perror("pthread_create");
return 1;
}
main_cycle(queue);
sleep(1);
return 0;
}
не подскажете, в чем проблема?