c - pthread 指针数组

标签 c arrays pthreads malloc realloc

我正在尝试动态分配一个 pthread 指针数组,但得到这个 glibc 错误:

*** glibc detected *** ./test: realloc(): invalid next size: 0x00000000084d2010 ***

代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int main(int argc, char** argv) {
    pthread_t **threads;
    int i;

    for(i=1;i<100;i++) {
        threads = realloc(threads, sizeof(pthread_t*)*i);
        threads[i] = malloc(sizeof(pthread_t));
    }

   return EXIT_SUCCESS;
}

我做错了什么?

最佳答案

  • 您应该初始化线程(重点是我的)。

C11 (n1570), § 7.22.3.5 The realloc function

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined.

  • sizeof(pthread_t *) * i 没有分配足够的内存来访问 thread[i]。您必须分配 ((sizeof(pthread_t *) * (i + 1))

关于c - pthread 指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071448/

相关文章:

c - 如何使用 OpenGL 绘制冰淇淋

c - malloc 和作用域

c - 信号量互斥锁防止死锁 - C 程序

c - 程序收到信号 SIGPIPE,Broken pipe

c++ - 如果没有线程阻塞信号,并且一个线程在 `sigwait()` 中,是否可以保证被阻塞的线程将接收到下一个信号?

c - 是否有任何工具可以为给定的正则表达式生成所有可能的有效/无效输入?

c - 我对指针增量有点困惑

javascript - 分隔字符串数组以创建表格行

c - 在 struct 中发出初始化数组

javascript - 双 for 循环中数组的奇怪行为 - JavaScript