C - 线程的内存损坏

时间:2014-12-31 02:34:48

标签: c pthreads errno

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

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(&amp; t-&gt; mutex,NULL))!= 0)//如果我评论这个,如果,       错误(C_ERRO_MUTEX_INIT,&#34; pthread_mutex_init()失败!&#34;);

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

分配:

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;

1 个答案:

答案 0 :(得分:2)

表面上看,你的问题是:

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

据推测,您的类型为t_data,但与t_data_thread无关。

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

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

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