[英]Segmentation fault using threads in C
我在这段代码中遇到段错误,但在任何地方都找不到问题。 它可以使用-lpthread进行编译,但是不会运行。 该程序从命令行获取一个整数,然后创建一个新线程以使用该值计算collatz猜想。 这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void print_con();
void calc_con(int *n);
int * values[1000];
int main(int argc, char * argv[])
{
int* num;
*num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);
pthread_join(thread, NULL);
print_con();
return 0;
}
void calc_con(int *n)
{
int i = 0;
int * x;
*x = *n;
*values[0] = *x;
while(*x > 1)
{
if(*x % 2 == 0)
*x /= 2;
else if(*x % 2 == 1)
{
*x *= 3;
*x++;
}
i++;
*values[i] = *x;
}
pthread_exit(0);
}
void print_con()
{
int i;
for(i = 0; i < 1000; i++)
{
if(*values[i] > 0)
printf("%d", *values[i]);
}
}
好的,您需要将void *
作为参数传递给pthread_create
,但是您仍然需要尊重基本知识:
int* num;
*num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, (void *)&calc_con, (void *)num);
这里*num = 15;
您正在将15
写入未初始化的指针 。 那是未定义的行为 。
我会做:
int num = 15;
pthread_t thread;
pthread_create(&thread,(pthread_attr_t*)NULL, &calc_con, &num);
请注意,您不必从非void的指针强制转换为void *
。 由于num
是在main
例程中声明的,因此您可以将指针安全地传递给线程。
请注意,正如dasblinkenlight指出的那样,您还必须在calc_con
修复接收端,它具有相同的问题:
int * x; // uninitialized pointer
*x = *n; // copy data "in the woods"
只需取消引用到局部变量,您就可以拥有自己的价值:
int x = *((int *)n);
还有一个:
int * values[1000];
是未初始化的整数指针数组,而不是您想要的整数数组。 它应该是
int values[1000];
然后
values[0] = x;
(并不是因为有很多*
运算符才是好代码)
您正在使用void*
将int
传递给线程。 这将在许多平台上运行,但是不能保证该数字将正确“往返”。 返回指针后,将其保存在取消引用的未初始化指针中,这是不正确的。
将指针传递给num
,然后将指针直接复制到x
:
void calc_con(void *n);
...
void calc_con(void *n) {
int i = 0;
int * x = n;
*values[0] = *x;
while(*x > 1) {
if(*x % 2 == 0) {
*x /= 2;
} else if(*x % 2 == 1) {
*x *= 3;
*x++;
}
i++;
*values[i] = *x;
}
pthread_exit(0);
}
...
int num = 15;
pthread_create(&thread,(pthread_attr_t*)NULL, calc_con, (void *)&num);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.