I am running into the error above trying to pass a file pointer in a struct to a thread. It is an assignment requirement to have the thread be passed this output file to write to.
//struct to pass file to thread 2
struct THEAD_TWO_DATA{
FILE *outputFile;
};
void* ThreadTwo(void *received_struct){
struct THEAD_TWO_DATA *struct_ptr = (struct THEAD_TWO_DATA*) received_struct;
fprintf(struct_ptr->outputFile, "%d\n", globalValue);
}
int main(){
struct THEAD_TWO_DATA *my_Struct;
my_Struct->outputFile = fopen("hw3.out", "w");
pthread_create(&th[1], NULL, ThreadTwo, &my_Struct);
}
CodePudding user response:
On this line: struct THEAD_TWO_DATA *my_Struct;
you declare a pointer to a structure.
But that pointer is not yet referencing anything valid!
Treat the pointer as a NULL pointer (although it might well be an invalid reference to some unknown part of memory), until you are SURE it is actually referencing valid memory.
On the next line: my_Struct->outputFile = fopen("hw3.out", "w");
, you try to assign a value in this un-initialized, invalid structure.
You need to be sure the pointer is referencing a valid object before trying to use it.
I recommend something like:
int main(){
struct THEAD_TWO_DATA my_Struct; // Not a reference, an actual structure
my_Struct.outputFile = fopen("hw3.out", "w");
pthread_create(&th[1], NULL, ThreadTwo, &my_Struct); // Pass a pointer to a structure.
}
Note that object my_Struct
is a temporary, local variable, and may not have a long enough duration for your use.