c - 在数组中声明指针到指针会导致分段错误
问题描述
我目前正在一个项目中实现我自己的线程 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];
。
解决方案
一种可能性是“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 *));
}
变量可能已被其他一些函数覆盖,例如越界数组写入。
推荐阅读
- r - 我想将数据框中的多个列与向量源隔离,并使用 R 将它们的数据类型从字符转换为数字
- mysql - 使用大数据更快地执行此查询的任何方法
- python-3.x - Djnago 模板 - 具有多个参数的 URL
- error-handling - 方案:为什么我会收到此错误:断言违规:错误类型的参数 [car (car #{Unspecific})
- c# - 异步更新多行立即更新1/4的行然后等待
- python - 在 Django 中,我的表单每次刷新时都会重新提交,我知道我可以通过重定向它来解决这个问题,但我也想将数据传递给我的模板
- python - 树视图中的行选择
- java - 将 JFrame 大小动态更改为 JTable 内容
- php - 多个mysqli对象互相覆盖
- python - 如何对齐两个 dask 数据帧的分区