I am trying to implement a solution based partly on the discussions below. Basically, I want to malloc()
in the main thread and free()
in a secondary thread. The discussions linked deal with LabWindows, but I think my question is more aimed at C programmers in general.
LabWindows: implementing thread safe queues that can handle string elements
I create a pointer to char in the main thread and allocate storage using malloc()
. I copy some data into the storage, and assign the pointer to an array element (CmtWriteTSQData
expects an array). This array gets passed to a thread safe queue.
In a secondary thread, the thread safe queue is read. The data is assigned to a new array.
How do I free the memory allocated within the secondary thread, as the pointer variable is no longer in scope?
Can I just call free()
on the array element? Or do I need to create another pointer to char in the secondary thread, copy the array element to it, and then call free()
on the pointer?
There doesn't appear to be a return value with free()
, so I can't figure out how to ensure the call succeeds.
// Main thread
char *ptr = NULL;
char *array1[1] = {0};
ptr = (char *) malloc (3 * sizeof (char));
strcpy (ptr, "hi");
array1[0] = ptr;
CmtWriteTSQData (queue, array1, 1, 0 NULL);
// Secondary thread
char *array2[1] = {0};
CmtReadTSQData (queue, array2, 1, 0, 0);
printf ("%s", array2[0]); // Prints "hi"
free (array2[0]); // Does this work?