Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing pointer char argument to function in thread

When I execute this code, I'm receiving a "segmentation error (core dumbed)".

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

}
like image 806
psykhagogos Avatar asked Nov 05 '25 02:11

psykhagogos


1 Answers

First you need to decide, how you want to manage the memory: is the memory allocated by caller, or inside the thread function.

If the memory is allocated by caller, then the thread function will look like:

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

If the memory is allocated inside the thread function, then you need to pass pointer-to-pointer:

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-
like image 198
Valeri Atamaniouk Avatar answered Nov 08 '25 00:11

Valeri Atamaniouk