C-线程内存损坏
我的记忆被破坏了,我不知道发生了什么。 这是我的一段代码:C-线程内存损坏,c,pthreads,errno,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() f
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");
然后在其他功能上:
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\u data
,但它与t\u data\u线程
无关
避免此类问题的常用习惯用法是:
t_data_thread *t = malloc(sizeof(*t));
我相信您没有显示检查分配是否成功的代码。您可能不应该这样写
errno
,尽管这也可能不是问题的原因。您是在创建线程之前还是之后执行此操作?与此代码相关的pthread\u create()
在哪里执行?另外,您的t\u data\u thread
结构的t->mutex
元素的定义可能是相关的。编译时是否收到任何编译器警告?您是否使用GCC并至少使用了-Wall-Wextra-Werror
?pthread_create()位于此代码之后,而我在结构上的互斥体是pthread_mutex\t。。。如果你想我可以发布更多的代码。。。我使用的是-Wall-W-Wmissing原型,我觉得pthread\u create()
是后来出现的。调用代码中如何分配t
?-W
是AFAICR的-Wextra
的旧名称。因此,如果代码中没有无法解释的警告,那么编译器就不会发现问题。因此,分析如何在调用函数中创建t
,可能是相关的。如果您发布更多代码,请显示t
的定义/分配,以及对您显示的函数的实际调用。(我假设您的注释“我还导入了errno lib”意味着您的代码中有#include
。它是一个标题,而不是真正的库。)以及t_数据_线程
?malloc(sizeof(t_数据))代码>-请检查t\u数据
并告诉我们您没有在typedef
中隐藏t\u数据线程*
指针类型。然后将malloc
固定为malloc(sizeof(*t))代码>编辑:好的,我们看到t\u data\u thread
。现在什么是t\u数据
?真的。。。这么愚蠢的错误。。。当我不使用线程时,t_数据是另一个结构。。。非常感谢,很抱歉这篇帖子发生了这些事情,多看一双眼睛会有所帮助。当然,成语也可以从一开始就避免这个问题。非常感谢乔纳森。在勾选此=P之前,必须检查您是否已经拥有火影忍者帽子
t_data_thread *t = malloc(sizeof(*t));