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

标签 c multithreading function char

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

#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/

相关文章:

c++ - 指针算术在数组之外有用途吗?

c - 如何获取SSDT地址

Chtons 或 inet_addr 数组

c - free() 内存错误

java - 使用 java 调用 Web 服务 URL

c - C 中的 Pthread_cond_wait

c++ - 在 C++ 中为字符串创建自定义函数

c - GTK+ 和 OpenGL

python - 根据三列的值有条件地交互式计算列

postgresql - 如何在 PostgreSQL 中列出用户定义的函数和过程