我遇到以下代码问题:
#define NTHREADS 100
int main(int argc, const char * argv[]) {
pthread_t threads[NTHREADS];
// ...
// Create threads
for (size_t i = 0; i < NTHREADS; ++i) {
pthread_create(threads + i, NULL, thread, NULL);
}
debugln("All %u threads are ready", NTHREADS);
// ...
for (size_t i = 0; i < NTHREADS; ++i) {
pthread_join(threads[i], NULL);
}
debugln("All threads terminated");
return 0;
}
debugln
的定义如下:
#define debugln(_fmt, _args...) fprintf(stderr, _fmt "\n", ##_args)
问题:
执行NTHREADS
设置为100
的程序时,valgrind
会多次输出此错误:
==2780== Invalid write of size 4
==2780== at 0x50976A2: vfprintf (vfprintf.c:246)
==2780== by 0x509CE53: buffered_vfprintf (vfprintf.c:2313)
==2780== by 0x509788D: vfprintf (vfprintf.c:1316)
==2780== by 0x50A24E6: fprintf (fprintf.c:33)
==2780== by 0x400ACA: main (in /tmp/cbuild_1413987921)
==2780== Address 0x7feffd158 is on thread 1's stack
但是当我将debugln
更改为
#define debugln(_fmt, _args...) printf(_fmt "\n", ##_args)
然后错误就消失了。
我已经尝试flockfile
&amp; funlockfile
并增加stacksize。两者都没有修复错误。 BTW valgrind --version
提供valgrind-3.7.0
修改
更改
时错误消失 #define NTHREADS 100
到
const unsigned NTHREADS = 100;
有人可以解释一下吗?