首页 > 解决方案 > 在数组中声明指针到指针会导致分段错误

问题描述

我目前正在一个项目中实现我自己的线程 API。

我有一个函数,我的目标是返回一个指向与唯一 ID 对应的给定线程的指针。我将其定义如下:

thread *getThread(Tid id){
    thread *want = threadsArr[id]; // threadsArr is an array that keeps track of created threads
    if (want != NULL && want->id == id){
        // free(want);
        printf("Arrived here");
        return want;
    }
    else {
        for (int i = 0; i < THREAD_MAX_THREADS; i++){
            want = threadsArr[i];
            if (want == NULL){
                continue;
            }
            else {
                if (want->id == id){
                    return want;
                }
            }
        }
    }
}

我运行了 gdb,它说该行thread *want = threadsArr[id];导致了分段错误。

我已经初始化了一个函数中的所有内容,如下所示:

void
thread_init(void)
{
    int idx = 0;
    for (idx = 0; idx < THREAD_MAX_THREADS; idx++){
        threadsArr[idx] = NULL;
    }
    currunThread = (thread *)malloc(sizeof(thread));
    currunThread->id = 0;
    currunThread->status = RUNNING;
    //initialize structure pointed to by ucp to the current user context of the calling thread
    getcontext(&(currunThread->context));

    readyThreads = (queue *)malloc(sizeof(queue));
    initQ(readyThreads);

    threadsArr[currunThread->id] = currunThread;
}

我以前在以前的程序中使用过这种方法并且没有出现 Seg Faults,所以我想知道为什么它现在发生了?

提前致谢。

编辑:如果我摆脱 getThread(Tid id) 中的 return 语句,我将不再收到 Sementation Fault。但是,如果我保留它,则会在我这样做时发生分段错误thread *want = threadsArr[id];

标签: cmultithreadingsegmentation-fault

解决方案


一种可能性是“id”变量超出范围:

thread *getThread(Tid id){
    if (id >= THREAD_MAX_THREADS)
        return NULL;

    thread *want = threadsArr[id];
...

你有一个失踪的';' 在可疑行的末尾。

IfthreadsArr被声明为全局指针,然后 malloc 到一个数组,如:

thread *threadsArr;

some_function()
{
    threadsArr = malloc(THREAD_MAX_THREADS * sizeof(thread *));
}

变量可能已被其他一些函数覆盖,例如越界数组写入。


推荐阅读