hello everyone I have some question about threads if for example I have some thread 1 which allocates some piece of the memory, and anohter thread (let’s assume 2) is killing thread 1 using pthread_cancel() or just using return what is going on with the peace of memory which it allocated? will be leak if thread 1 didn’t free this piece of memory? thanks in advance for any answer
edited
just to make it clearer, as I know pthread_cancel() kills thread, but what is going on with its memory when I kill it? In case of return all thread will be dead if 1 is the main thread
Yes, it will leak memory in that case. C does not have any garbage collection — if you allocate memory and fail to free it, it will be leaked, plain and simple.
If you want to avoid leaking memory, don’t call
pthread_cancel. Make your threads exit gracefully by setting a flag asking them to exit, and then when they detect that that flag is set, they can free their memory and kill themselves by returning from their thread procedures or by callingpthread_exit.Alternatively, you can set a thread cleanup handler by calling
pthread_cleanup_push, which will get called when your thread exits or gets canceled by a call topthread_cancel. You can use a handler function which will free any allocated memory you have outstanding.