Segfault发布资源

时间:2016-05-09 16:53:26

标签: c++ multithreading

我在代码中删除trainArray时遇到了一个seg错误。我正在尝试获取Train对象的所有指针并删除它们。我在这里做错了什么?

  pthread_t tidArray[NUM_TRAINS];
  Train* trainArray[NUM_TRAINS];

  for  (int i = 0;  i < NUM_TRAINS;  i++){
    trainArray[i] = new Train(TRAIN_NAME_ARRAY[i],TRAIN_TRANSIT_TIME_MSECS[i]);
  }
  int trainInd  = 0;

  for(trainInd = 0;trainInd<NUM_NORTHERNLY_TRAINS;trainInd++){
    pthread_create(&tidArray[trainInd],NULL,initiallyNorthernly,(void*)trainArray[trainInd]);

  for(trainInd = NUM_SOUTHERNLY_TRAINS;trainInd<NUM_TRAINS;trainInd++){
    pthread_create(&tidArray[trainInd],NULL,initiallySouthernly,(void*)trainArray[trainInd]);
  }
    for  (int i = 0;  i < NUM_TRAINS;  i++){
      trainArray[i] = NULL;
      pthread_join(tidArray[i],(void**)&trainInd);
      delete trainArray[NUM_TRAINS];
    }
    return(EXIT_SUCCESS);
}

1 个答案:

答案 0 :(得分:1)

当你写这篇文章时:

delete trainArray[NUM_TRAINS];

我很确定你的意思是:

delete trainArray[i];

...特别是看到第一个引用了一个不存在的数组元素。

我建议您使用一个不错的std::vector,这样就不会犯这样的愚蠢错误。