【发布时间】:2014-12-31 02:34:47
【问题描述】:
我有一个内存损坏,我不知道发生了什么。 有一段我的代码:
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, ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_init() 失败!");
代码运行但随后会在互斥锁上失败...我还导入了 errno 库... 提前谢谢你!
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;
【问题讨论】:
-
你可能不应该那样写信给
errno,尽管它也可能不是问题的原因。您是在创建线程之前还是之后执行此操作?与此代码相关的pthread_create()在哪里执行?此外,t_data_thread结构的t->mutex元素的定义可能是相关的。编译时是否收到任何编译器警告?您是否使用 GCC 并至少使用-Wall -Wextra -Werror? -
pthread_create() 出现在此代码之后,我在结构上的互斥锁是 pthread_mutex_t ...如果您愿意,我可以发布更多代码...我正在使用 -Wall -W -Wmissing-prototypes
-
我有一种感觉,
pthread_create()来晚了。调用代码中t是如何分配的?-W是-Wextra的旧名称,AFAICR。因此,如果代码中没有无法解释的警告,则很可能不存在编译器可检测到的问题。因此,分析t在调用函数中是如何创建的可能是相关的。如果您发布更多代码,请显示t的定义/分配,以及对您显示的函数的实际调用。 (我假设您的评论“我还导入了 errno lib”意味着您的代码中有#include <errno.h>。它是一个标题,而不是真正的库。) -
而 what 包含
t_data_thread? -
malloc(sizeof(t_data));- 请检查t_data并告诉我们您没有隐藏t_data_thread*指针输入typedef.然后将malloc修复为malloc(sizeof(*t));编辑:好的,我们看到t_data_thread。现在t_data是什么?