0

由于这个等式末尾的 free(),我得到了错误分段错误......

我不需要释放临时变量 *stck 吗?或者因为它是一个本地指针并且从未通过 malloc 分配内存空间,编译器会为我清理它?

void * push(void * _stck)
{

  stack * stck = (stack*)_stck;//temp stack
  int task_per_thread = 0; //number of push per thread


  pthread_mutex_lock(stck->mutex);
  while(stck->head == MAX_STACK -1 )
  {
    pthread_cond_wait(stck->has_space,stck->mutex);
  }

  while(task_per_thread <= (MAX_STACK/MAX_THREADS)&&
        (stck->head < MAX_STACK) &&
    (stck->item < MAX_STACK)//this is the amount of pushes
                //we want to execute
       )
  { //store actual value into stack
    stck->list[stck->head]=stck->item+1;
    stck->head = stck->head + 1;
    stck->item = stck->item + 1; 
    task_per_thread = task_per_thread+1; 
  }

  pthread_mutex_unlock(stck->mutex);


  pthread_cond_signal(stck->has_element);


  free(stck);


  return NULL;
}
4

1 回答 1

0

编辑:您完全改变了问题,所以我的旧答案不再有意义。我会尝试回答新问题(旧答案仍在下方),但作为参考,下次请只问一个新问题而不是更改旧问题。

stck是一个指针,您设置为指向与指向相同的内存_stck。指针并不意味着分配内存,它只是指向已经(希望)分配的内存。例如,当您这样做时

char* a = malloc(10);  // Allocate memory and save the pointer in a.
char* b = a;           // Just make b point to the same memory block too.
free(a);               // Free the malloc'd memory block.
free(b);               // Free the same memory block again.

你释放相同的内存两次。

——老答案

在 push 中,您设置stck指向与相同的内存块_stck,并在调用结束时释放堆栈(从而从每个线程调用一次公共堆栈上的 free())

删除free()呼叫,至少对我而言,它不再崩溃。释放堆栈可能应该在main()加入所有线程之后完成。

于 2012-01-29T10:03:23.567 回答