【发布时间】:2010-08-26 14:46:11
【问题描述】:
这与我一直在讨论 here 和 here 的问题有关,但由于我的调查使我远离了 STL 作为潜在问题,而将“新”作为我的克星,我认为最好开始一个新线程。
重申一下,我使用的是嵌入式平台供应商提供的 arm-linux 交叉编译器(版本 2.95.2)。
当我在我的 Linux PC 上运行以下应用程序时,它当然永远不会失败。但是,在嵌入式设备上运行它时,我每次都会遇到分段错误。使用“malloc”永远不会失败。使用互斥锁同步“新”分配将停止该问题,但这在我的主应用程序中不实用。
谁能说明为什么会发生这种情况,或者有什么想法可以解决这个问题?
谢谢。
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t _logLock = PTHREAD_MUTEX_INITIALIZER;
static void* Thread(void *arg)
{
int i = 0;
while (i++ < 500)
{
// pthread_mutex_lock(&_logLock);
char* myDyn = (char*) new char[1023];
// char* buffer = (char*) malloc(1023);
// if (buffer == NULL)
// printf("Out of mem\n");
// free(buffer);
delete[] myDyn;
//pthread_mutex_unlock(&_logLock);
}
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
int threads = 50;
pthread_t _rx_thread[threads];
for (int i = 0; i < threads; i++)
{
printf("Start Thread: %i\n", i);
pthread_create(&_rx_thread[i], NULL, Thread, NULL);
}
for (int i = 0; i < threads; i++)
{
pthread_join(_rx_thread[i], NULL);
printf("End Thread: %i\n", i);
}
}
【问题讨论】:
-
你应该尝试用 try/catch 包装 new/delete 并在 std::bad_alloc 上进行例外处理,看看你从那里得到了什么。
-
您是否使用
-pthread标志进行编译和链接?
标签: c++ linux arm segmentation-fault new-operator