执行此代码时,我收到“段错误(内核已转储)”。
#include <pthread.h>
#include <stdio.h>
void function(char *oz){
char *y;
y = (char*)oz;
**y="asd";
return NULL;
}
int main(){
char *oz="oz\n";
pthread_t thread1;
if(pthread_create(&thread1,NULL,function,(void *)oz)){
fprintf(stderr, "Error creating thread\n");
return 1;
}
if(pthread_join(thread1,NULL)){
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("%s",oz);
return 0;
}
最佳答案
首先,您需要决定如何管理内存:是调用方分配的内存,还是线程函数内部的内存。
如果内存是由调用方分配的,则线程函数将如下所示:
void *function(void *arg)
{
char *p = arg;
strcpy(p, "abc"); // p points to memory area allocated by thread creator
return NULL;
}
用法:
char data[10] = "oz"; // allocate 10 bytes and initialize them with 'oz'
...
pthread_create(&thread1,NULL,function,data);
如果内存是在线程函数内部分配的,那么您需要传递指针到指针:
void *function(void *arg)
{
char **p = (char**)arg;
*p = strdup("abc"); // equivalent of malloc + strcpy
return NULL;
}
用法:
char *data = "oz"; // data can point even to read-only area
...
pthread_create(&thread1,NULL,function,&data); // pass pointer to variable
...
free(data); // after data is not needed - free memory-
关于c - 将指针char参数传递给线程中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320354/