Skip to content

Commit

Permalink
vumeter-qt: Do not use variable length arrays
Browse files Browse the repository at this point in the history
They are not officially supported in C++.
  • Loading branch information
radioactiveman committed Dec 18, 2023
1 parent 1f02fb1 commit 9154d19
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/vumeter-qt/vumeter_qt_widget.cc
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ void VUMeterQtWidget::render_multi_pcm (const float * pcm, int channels)
{
nchannels = aud::clamp(channels, 0, max_channels);

This comment has been minimized.

Copy link
@stefanos82

stefanos82 Dec 18, 2023

If nchannels was declared here as constexpr, it would have worked as you wanted, without the need to introduce new[] / []delete operators.

This comment has been minimized.

Copy link
@radioactiveman

radioactiveman Dec 19, 2023

Author Member

True, however nchannels is not used only here.
It's declared in the header to be accessed in multiple places and cannot be made constexpr.

This comment has been minimized.

Copy link
@stefanos82

stefanos82 Dec 19, 2023

Ah yes, you are right.

I guess you could play it safe by using smart pointers, because why not...

I have tested the following example and works as expected:

#include <array>
#include <iostream>
#include <memory>

int main()
{
    int nchannels = 2;
    auto peaks = std::make_unique<float[]>(nchannels);
    // it should print '2' for number of elements
    std::cout << sizeof(peaks)/sizeof(peaks[0]) << '\n';
    return 0;
}

I've even took it even further to double-check for memory leaks via godbolt, just in case: -Wall -Wextra -Werror -Wpedantic -std=gnu++17 -fsanitize=address,undefined


float peaks[nchannels];
float * peaks = new float[nchannels];
for (int channel = 0; channel < nchannels; channel++)
{
peaks[channel] = fabsf(pcm[channel]);
Expand Down Expand Up @@ -120,6 +120,8 @@ void VUMeterQtWidget::render_multi_pcm (const float * pcm, int channels)
last_peak_times[i].start();
}
}

delete[] peaks;
}

void VUMeterQtWidget::redraw_timer_expired()
Expand Down

0 comments on commit 9154d19

Please sign in to comment.