PThread Malloc上的分段错误

时间:2016-07-03 16:09:33

标签: c segmentation-fault pthreads

首先让我先发布一下代码:

#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);
    }
}

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

1 个答案:

答案 0 :(得分:0)

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));