C语言 PThread Malloc上的分段错误



首先让我从发布代码开始:

#include <pthread.h>
#include<stdlib.h>
//64 BITS -ALL 32 bit Arch
//32 BIT - UNIX 64 bit arch
//64 BIT - WINDOWS 64 bit arch
long long sum = 0;
static enum turn
{
  PING,
  PONG
}def;
struct threads_util
{
  pthread_t *t_id;
  pthread_attr_t *attr;
  void (*init_attr)(pthread_attr_t *);
}; 
void init_attr_fn(pthread_attr_t *attr)
{
  pthread_attr_init(&attr);
}
void* sum_runner(void* arg)
{
    long long* limit_ptr = (long long *) arg;
    long long limit = *limit_ptr;//Derefrencing
    for(long long i=0; i<=limit; i++)
        sum += i;
    printf("Sum is %lld n", sum);
    pthread_exit(0);
}
void ping()
{
  puts("Ping");
  def = PONG;
}
void pong()
{
  puts("Pong");
  def = PING;
}
pthread_t * all_thread(pthread_t *t_id)
{
  t_id = malloc(sizeof(pthread_t));
  return t_id;
}
int main(int argc, char **argv)
{
    if(argc<2)
    {
    puts("Usage ./objFile <num 1> <num 2> .. <num n>"); 
        exit(1);
    }
    int args = argc-1;
    long long limit = atoll(argv[1]);
    def = PING;
   struct threads_util *threads[args];
   for (int i=0; i<args; i++)
    threads[i]->t_id = all_thread(threads[i]->t_id);
    puts("In");    
   for(int i=0; i<args; i++)
   {
      threads[i]->init_attr = init_attr_fn;
      threads[i]->init_attr(threads[i]->attr);
      pthread_create(threads[i]->t_id,threads[i]->attr,sum_runner,&limit);
   }
    //Begin -Main Functions
    for(int i=0; i<= 10; i++)
    {
    if(def == PING)
           ping();
        else if(def == PONG)
           pong();
        else
           puts("UNKOWN PI-PO");           
    }
    //End - Main Functions
    for(int i=0; i<args; i++)
    {
      pthread_join(threads[i]->t_id,NULL);
    }
}

你可以看到我有一个puts("In"),在main函数中,就在for循环之后,当我调用all_thread args次数。根据我的调试技巧,用for循环调用函数argc数次是问题所在。在我们做所有的分配策略之前,我在调用线程函数时遇到了一个问题,当然会导致分割错误。threads[i]->init_attr(threads[i]->attr);。非常感谢您的帮助。

struct threads_util *threads[args];

意味着定义一个指向struct threads_util指针数组。但是你实际上并没有创建任何struct threads_util所以这一行:

threads[i]->t_id = all_thread(threads[i]->t_id);

是非法的,因为它写入未分配的内存。

您需要先为struct threads_util分配内存:

for (int i=0; i<args; i++)
    threads[i] = malloc(sizeof(struct threads_util));

最新更新