Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

zsh: bus error when passing struct to thread

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

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

But its a start….

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading