此代码运行但不断遇到段错误(核心转储)。不确定问题出在哪里,我尝试为线程运行不同的变量,但在尝试使用 2 运行时会产生一个大错误。
*** thread 21474836484 sees value 32
*** thread 21474836484 sees value 33
*** thread 38654705672 sees value 25
*** thread 34359738375 sees value 29
*** thread 34359738375 sees value 30
Thread 34359738375 sees final value 31
*** thread 21474836484 sees value 31
*** thread 38654705672 sees value 32
*** thread 21474836484 sees value 33
*** thread 38654705672 sees value 34
*** thread 21474836484 sees value 35
Thread 21474836484 sees final value 36
*** Error in `./treadcreator': munmap_chunk(): invalid pointer: 0x00007ffeab9a33bc ***
*** thread 8589934593 sees value 29
*** thread 8589934593 sees value 30
*** thread 8589934593 sees value 31
Segmentation fault (core dumped)
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
struct my_thread_info {
long which;
};
int SharedVariable = 0;
void *SimpleThread(void *data) {
int num, val;
struct my_thread_info *info = data;
for (num = 0; num < 20; num++) {
if (random() > RAND_MAX / 2)
usleep(10);
val = SharedVariable;
printf("*** thread %ld sees value %d\n", info->which, val);
SharedVariable = val + 1;
}
val = SharedVariable;
printf("Thread %ld sees final value %d\n", info->which, val);
free(info);
return NULL;
}
int main(int argc, char **argv) {
int j = 0, isDigit = 1;
while (j < strlen(argv[1])) {
isDigit = isdigit(argv[1][j]);
if (isDigit == 0) break;
j++;
}
if (isDigit == 1) {
int num_threads = atoi(argv[1]); // Convert first argument to integer.
pthread_t threads[num_threads];
int args[num_threads];
int i = 0;
for (i = 0; i < num_threads; i++) {
args[i] = i + 1;
if (pthread_create(&threads[i], NULL, SimpleThread, &args[i]) != 0) {
printf("error: Cannot create thread # %d\n", i + 1);
break;
}
}
int a = 0;
for (a = 0; a < num_threads; i++)
if (pthread_join(threads[a], NULL) != 0)
printf("error: Cannot join thread # %d\n", a + 1);
} else
printf("Enter a valid number for number of threads to be created\n");
return 0;
}
最佳答案
一般来说,malloc
或 free
内的任何崩溃(在本例中,munmap_chunk
由 free
调用)很可能是堆损坏的结果。
在这种特殊情况下,您free(info)
,但没有malloc
它(info
指向堆栈变量 >args[i]
)。
释放未分配的内存是堆损坏的一个具体实例。其他原因:释放
两次、malloc
溢出缓冲区等。
找到这个(和类似)错误的一个好方法是在 Valgrind 下运行程序。或(更好)Address Sanitizer .
关于c - 使用线程的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51233127/