我正在尝试动态分配一个 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/