将指针 char 参数传递给线程中的函数

2023-12-05

当我执行此代码时,我收到“分段错误(核心转储)”。

#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;
}

Usage:

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;
}

Usage:

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-
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将指针 char 参数传递给线程中的函数 的相关文章

随机推荐