|Subject:||Re: [Discuss-gnuradio] Why are malloc_<type> in gr::fft?|
|Date:||Thu, 23 Apr 2015 10:53:26 +0200|
|User-agent:||Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.6.0|
you just `malloc(...)` when you need to; why would you, in general, need GNU Radio to wrap that simple libc call, especially since there's calloc?
gr::fft needs these fftw_mallocs because FFTW (which is the FFT library underneath) expects specially aligned memory, and therefore offers it's own fftwf_malloc; thus, we need to wrap this up. It's an FFTW-speciality, and shouldn't be used for different things than memory that FFTW works on.
When you work with fftw (which is a C library) in C++, you'll notice that C++ is a bit more strict than C when it comes to pointer types, and you have to cast around the pointer type just to get it working. Since that is a bit ugly to do in-line, there's these malloc abstractions that you've mentioned.
Generally, as we try to write beautiful C++, we don't malloc much -- new might be your friend if you actually want to work with arrays.
However, GNU Radio is a bit doomed when it comes to having beautiful, type-safe code, because the core concept of gr_buffer basically is that buffers between blocks are just memory regions, not data of a specific type -- hence all the "ugly" pointer casting that happens in about every work().
There's a lot of places where `malloc` is really handy in our code, for example in the DVB decoders, where structures for decoding need to dynamically be allocated, or in the GUIs, where you often just want to have a bit of memory representing your framebuffer. But as a rule of thumb, you should try to avoid dynamically allocating memory manually (using malloc) as much as possible -- it's just one of the most popular causes for hard-to-debug bugs.
It's often practical to use `std::vector<type> myvector(number_of_elements)` instead -- it does the allocation for you, allows for resizing, and you can, just like with malloc, get the address of the first element ( `&(myvector)` ) . As a bonus, `myvector[x]` always actually has the right type, and you don't need to first cast the return value of malloc to a pointer of whatever you want to have.
If you don't need the resizing of `std::vector`, just the dynamic allocation, `std::array` is also awesome; both being STL containers offer a great deal of functionality that you'd have to implement yourself if you just go a C-style array in some malloc'ed memory.
On 04/23/2015 10:18 AM, Jeon wrote:
|[Prev in Thread]||Current Thread||[Next in Thread]|