简体   繁体   English

C++ 代码的分段错误(核心转储)

[英]segmentation fault (core dumped) for C++ code

I wrote code for multithreaded sort application in C++ that does merge sort with array of random number but I couldn't test this because there's "segmentation fault (core dumped)".我在 C++ 中为多线程排序应用程序编写了代码,该代码确实与随机数数组合并排序,但我无法对此进行测试,因为存在“分段错误(核心转储)”。 I think there's problem in main function but I have no idea for which part of code have problem.我认为主要的 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;
}

I tried to test on linux and used this command for compile我尝试在 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);

Creating two threads but waiting for 4 threads to join???创建两个线程但等待 4 个线程加入??? Accessing threads[2] will give you core dump.访问线程[2] 将为您提供核心转储。

Try to generate debug binary with -g option, enable core dump on your system and analyze core dump with gdb debugger.尝试使用 -g 选项生成调试二进制文件,在系统上启用核心转储并使用 gdb 调试器分析核心转储。 gdb will show you exact line that is causing the core dump. gdb 将向您显示导致核心转储的确切行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM