gpt4 book ai didi

C - 线程内存损坏

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:38 24 4
gpt4 key购买 nike

我有一个内存损坏,我不知道发生了什么。有一段我的代码:

void create_threads(t_data_thread *t, int max_threads){

int i;

/*Starts mutex */
if ((errno = pthread_mutex_init(&t->mutex, NULL)) != 0) // if I comment this if,
ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_init() failed!"); // the code runs

/* Initializate the condition variable*/
if ((errno = pthread_cond_init(&t->cond, NULL)) != 0)
ERROR(C_ERRO_CONDITION_INIT, "pthread_cond_init() failed!");
t->total = 0;
t->writing_index = 0;
t->reading_index = 0;
t->stop = 0;


t->thread_count = MIN(t->num_files, max_threads);


pthread_t * tids = malloc(sizeof(pthread_t)*t->thread_count); // memorry corruption...

exit(0); // <- for test what is making the error
t->buffer = malloc(sizeof(char*) * t->thread_count*2);


for (i = 0; i < t->thread_count; i++){
if ((errno = pthread_create(&tids[i], NULL, consumer, t)) != 0)
ERROR(C_ERRO_PTHREAD_CREATE, "pthread_create() failed!");
}

producer(t);

/* Enter critical section */
if ((errno = pthread_mutex_lock(&(t->mutex))) != 0) {
WARNING("pthread_mutex_lock() failed");
}

t->stop = 1;

/* broadcast waiting threads */
if ((errno = pthread_cond_broadcast(&(t->cond))) != 0) {
WARNING("pthread_cond_signal() failed");

我不知道发生了什么,如果我评论:

if ((errno = pthread_mutex_init(&t->mutex, NULL)) != 0) // if I comment this if, ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_init() failed!");

代码运行但随后会在互斥体上失败...我还导入了 errno lib...提前谢谢您!

t分配:

t_data_thread *t = malloc(sizeof(t_data));
t->thread_count = maxThreads;
t->num_files = 0;

然后是其他功能:

t-> num_files =0;
t->filesArray = (char**)malloc(sizeof(char*));

在一个循环中我得到了:

t->filesArray = realloc(t->filesArray, (t->num_files + 1) * sizeof(char*));

t->filesArray[t->num_files] = strdup(str);
t->num_files++;

结构:

typedef struct 
{
char **wordsArray;
int wordCounter;
int sizeInbyte;
long int curPos;
int num_files;
char **buffer;
int writing_index;
int reading_index;
int total;
int stop;
int thread_count;
char **filesArray;
pthread_mutex_t mutex;
pthread_cond_t cond;
}t_data_thread;

最佳答案

从表面上看,您的问题是:

t_data_thread *t = malloc(sizeof(t_data));

据推测,您有一个类型t_data,但它与t_data_thread 无关。

避免此类问题的常见习惯用法是:

t_data_thread *t = malloc(sizeof(*t));

我相信您跳过了显示检查分配是否成功的代码。

关于C - 线程内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27715447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com