Page 1 of 1

segmentation fault on second mmal_port_destroy

Posted: Thu Feb 07, 2019 2:29 pm
by inac
Dear all,

When I call mmal_port_destroy once it works fine. But if I (accidentally) destroy it twice like

Code: Select all

    if (m_pool)
        mmal_port_pool_destroy(output, m_pool);
    
    if (m_pool)
        mmal_port_pool_destroy(output, m_pool);
Then the second time it crashes with a segmentation fault. On what do I need to check to void the segmentation fault? After the first time mmal_port_destory the m_pool and output are still not NULL and the queue in it keeps the same size.

Re: segmentation fault on second mmal_port_destroy

Posted: Sun Feb 10, 2019 3:04 pm
by Doub
You shouldn't use m_pool after calling destroy. This is C (as oppposed to C++), the mmal_port_pool_destroy function cannot set your pointer to NULL, the caller is responsible for that. This is just like calling "free" twice on the same pointer.

Re: segmentation fault on second mmal_port_destroy

Posted: Tue Feb 12, 2019 8:14 am
by inac
Oke thank you for you answer! Apparently it's not something inside the pool function.

Re: segmentation fault on second mmal_port_destroy

Posted: Tue Feb 12, 2019 9:35 am
by 6by9
Read the implementation
https://github.com/raspberrypi/userland ... til.c#L294
and then mmal_pool_destroy at
https://github.com/raspberrypi/userland ... ool.c#L195

This is C, not C++. Things don't get passed by reference (a construct that I find fairly hideous).
As Doub states, it is the same as

Code: Select all

char *buffer = (char*)malloc(2048);
free(buffer);
free(buffer);
although slightly worse as it will dereference the pointer into memory that has been freed.

It could be implemented that mmal_port_destroy takes a MMAL_POOL_T **pool, so that it can then nuke the pool pointer, but that is not the normal way to do things in C.
The sensible way to code it is

Code: Select all

   if (m_pool) {
        mmal_port_pool_destroy(output, m_pool);
        m_pool = NULL;
     }
    
    if (m_pool) {
        mmal_port_pool_destroy(output, m_pool);
        m_pool = NULL;
     }
As it happens mmal_port_pool_destroy checks for being passed a NULL pool handle and returns immediately if so, therefore your conditional isn't required.

Re: segmentation fault on second mmal_port_destroy

Posted: Thu Feb 14, 2019 9:02 am
by inac
Thank you! That give a nice look at the idea behind it.