1

The code is as follows:

    pthread_t *threads;
    pthread_attr_t pta;

    threads = (pthread_t *) malloc(sizeof(pthread_t) * NumThreads);
    pthread_attr_init(&pta);
    for(i=0; i<NumThreads; i++) {
        pthread_create(&threads[i], &pta, (void*(*)(void*))Addup, (void*)(i+1));
    } 

    for(i=0; i<NumThreads; i++) {
        ret_count = pthread_join(threads[i], NULL); 
    }

    pthread_attr_destroy(&pta);

    free(threads); // Is this needed?

So, is it necessary to free(threads)? Does the pthread_attr_destroy(&pta) free the memory resources?

mining
  • 3,557
  • 5
  • 39
  • 66
  • 1
    I don't know pthreads very much, but I think `pthread_attr_destroy()` and `free()` have no related things. Don't you think so? – ikh Feb 03 '15 at 11:51
  • 1
    @ikh, thank you for replying. I'm not sure if the `pthread_attr_destroy()` would release the resources of the related threads. I looked this piece of code in the Example 1.2 of http://cdac.in/index.aspx?id=ev_hpc_hypack_pthread_basic_calls, it seems there isn't the `free(threads)`, thus I'm not sure if the author had forgot that. I think it is necessary. But I'm not familiar with Pthreads, thus I'm not sure if the `pthread_attr_destroy()` would also release its resources about the threads. – mining Feb 03 '15 at 11:58

2 Answers2

3

It is a s simple as: Each call to malloc() needs exactly one call to free() to not leak memory.

free(threads); // Is this needed?

So yes absolutly, it is needed!

This is totally unrelated to the PThread-API.

alk
  • 69,737
  • 10
  • 105
  • 255
  • Thank you! Sir. I use the valgrind to analyze the code, if no `free(threads)`, it will report the memory leak. – mining Feb 09 '15 at 04:25
1

After a little searching, I think that's needed.

pthread_attr_destroy does destroy pthread_attr_t which was made by pthread_attr_init. That's all.

And if pthread_attr_destroy really does free the memory, how about this example?

pthread_t thrd;
pthread_attr_t pta;

pthread_attr_init(&pta);
thrd = pthread_create(...);
...
pthread_attr_destroy(&pta); // What memory should he free?
ikh
  • 10,119
  • 1
  • 31
  • 70
  • Hi, thank you! This is also what I'm concerning. I'm not familiar with the intrinsic mechanism of Pthreads, thus I'm not sure. Could you help give some advice on detecting this kind of memory leak? or some tools on this work? Because I usually concern the memory problem, thus I don't use those tools often. – mining Feb 03 '15 at 12:12
  • @hubberwinston google with "memory leak detection". I guess [valgrind](http://valgrind.org/) can be recommended. – ikh Feb 03 '15 at 12:16
  • Yes! When I use valgrind to check the memory leak, it shows the `free(threads)` is really needed! – mining Feb 03 '15 at 12:31