[英]segmentation fault (core dumped) for C++ code
我在 C++ 中為多線程排序應用程序編寫了代碼,該代碼確實與隨機數數組合並排序,但我無法對此進行測試,因為存在“分段錯誤(核心轉儲)”。 我認為主要的 function 有問題,但我不知道代碼的哪一部分有問題。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#define MAX 20
#define THREAD_MAX 2
using namespace std;
int a[MAX]; //array for test
int part = 0;
void merge(int low, int mid, int high)
{
//merge function for merge 2 parts
}
void merge_sort(int low, int high)
{
//merge sort function
}
void* merge_sort(void* arg)
{
//thread function for multithreading
}
int main()
{
for (int i = 0; i < MAX; i++)
a[i] = rand() % 100;
pthread_t threads[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++)
pthread_create(&threads[i], NULL, merge_sort, (void*)NULL);
for (int i = 0; i < 4; i++)
pthread_join(threads[i], NULL);
merge(0, (MAX / 2 - 1) / 2, MAX / 2 - 1);
merge(MAX / 2, MAX / 2 + (MAX - 1 - MAX / 2) / 2, MAX - 1);
merge(0, (MAX - 1) / 2, MAX - 1);
// displaying sorted array
cout << "Sorted array: ";
for (int i = 0; i < MAX; i++)
cout << a[i] << " ";
return 0;
}
我嘗試在 linux 上進行測試並使用此命令進行編譯
g++ -pthread filename.cpp
#define THREAD_MAX 2
pthread_t threads[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++)
pthread_create(&threads[i], NULL, merge_sort, (void*)NULL);
for (int i = 0; i < 4; i++)
pthread_join(threads[i], NULL);
創建兩個線程但等待 4 個線程加入??? 訪問線程[2] 將為您提供核心轉儲。
嘗試使用 -g 選項生成調試二進制文件,在系統上啟用核心轉儲並使用 gdb 調試器分析核心轉儲。 gdb 將向您顯示導致核心轉儲的確切行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.