#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct arg_struct{
char* arg1;
char* arg2;
};
void *find_substr_count(void *context){
char* newStr;
struct arg_struct* arguments = context;
newStr = (*arguments).arg1;
printf("newstr: %s\n", (*newStr));
}//end find_substr_count
main(void){
pthread_t thread1;
/* Create independent threads each of which will execute function */
int iret1;
FILE* fp;
char* str1;
char* str2;
char* str3;
char* str4;
size_t len = 0;
ssize_t read;
int count = 0;
fp = fopen("./string.txt", "r");
if(fp == NULL){
exit(EXIT_FAILURE);
}
read = getline(&str1, &len, fp);
str3 = str1;
printf("Retrieved line of length %zu:\n", read);
read = getline(&str2, &len, fp);
str4 = str2;
printf("%s\n", str1);
printf("Retrieved line of length %zu:\n", read);
printf("%s\n", str2);
struct arg_struct args;
args.arg1 = str3;
args.arg2 = str4;
free(str1);
free(str2);
iret1 = pthread_create(&thread1, NULL, *find_substr_count, &args);
pthread_join(thread1, NULL);
printf("Thread 1 returns:%d", iret1);
fclose(fp);
exit(0);
}//end main
My c program reads two lines from a text file and initializes them as str1, and str2. Then I set them to str3, and str4, and free the memory on str1, and str2. I set str3, and str4 as the members of my struct "arg_struct" so that I can have multiple arguments go in to my function: "find_substr_count((void context))", after calling pthread_create. But when I try to print the arg1, after dereferencing, I get "(null)" as the output. When I try to print arg2, after dereferencing, I get a segmentation fault error. I feel like this is a pointer problem but I can't find out what I'm doing wrong. I am doing this on a a linux VM with 4 CPUs, that's why I can use POSIX pthreads. I need to get the right values for my function. Please help!
I have tried to use st1, and str2 directly to the function, and to free them after pthread_join, i get seg fault. I have tried using args.arg1 = &str3, args.arg2 = &str4, and i get a seg fault before printing length of str2 in output. I have tried using void* as the data type for arg_struct inside pthread_create but I get a compiler error: "cannot convert to pointer type". Im expecting for my program to print the first line of the text file, to print in my "find_substr_count((void context))" function. The text file is in the same directory of number_substring.c and is called string.txt.