c - pThreads 段错误

标签 c pthreads malloc

这是传递给线程声明的结构:

   typedef struct  {
              int rowsPerThread;                    
              int StartingRow;                     
              double co[WIDTH][HEIGHT][2];          
              uint64_t total_iters;                

      } thdata;

下面是我如何使用它:(注意 malloc)

  /* data passed to each thread */
  thdata *data[threads_num];


  /* create threads */
  for (i=0; i<threads_num; i++)
  {
      data[i]=(thdata *)malloc(sizeof(thdata));
      data[i]->rowsPerThread= rowsPerThread;
      data[i]->StartingRow= i*rowsPerThread;

      for (i=i*rowsPerThread; i<rowsPerThread; i++)
      memcpy(data[i]->co[i], Coordinates[i], sizeof (Coordinates) * HEIGHT * 2);


      pthread_create(&thread[i], NULL, (void *) &threaded_calc, (void *) &data[i]);   
      free(data[i]);
  }

我认为 malloc() 有问题。

它给我段错误。

最佳答案

问题是您在 for block 中 free 您的 data[i],就在创建 pthread< 之后 并且由于您不知道 thread 何时启动,因此 data[i] 可能在 之前被释放>threadscheduler 有效启动。

因此,您应该在线程体内调用free

关于c - pThreads 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865106/

相关文章:

C/C++ : is GOTO faster than WHILE and FOR?

c - 为什么我不能将C代码中逻辑表达式的返回结果存储到变量中?

multithreading - 如何解决 FlasCC 中巨大的 pthread 内存成本?

c - Malloc 重新分配免费

c - C 中 malloc 中的指针大小问题

C 哈希表问题,一切都具有相同的值(value)

c - 打印一个 malloc() 声明的数组 - 打印越界的非常短的代码?

c - C 程序如何将空格参数传递给 libc system(3) 调用?

php - 在 Ubuntu 上启用 ZTS 重新编译 PHP

c++ - 查找僵尸线程的来源