Valgrind error -Address在分配后为零字节 - C/C++

Viv*_*V K 0 c++ arrays valgrind

我正在为我的项目进行内存泄漏.我收到一个错误,我无法理解它的根本原因.我的代码很大,所以我会在这里放置需要的块.

基本上我在一个函数中有一个数组find_pulses,我动态分配如下:

float*rmsArray;
    rmsArray = (float*)malloc((N-pulse_samplewidth+1)*sizeof(float));
Run Code Online (Sandbox Code Playgroud)

我调试到这一点,发现它N-pulse_samplewidth+1不是零.(实际上~2 ^ 21)

我将值填充到此数组中,如下所示:

for (int loop1 = 0; loop1 < N-pulse_samplewidth; ++loop1) {
// populate rms array here.
}
Run Code Online (Sandbox Code Playgroud)

我将此数组发送到另一个名为findpeakthis的函数:

 int* ans = findpeak(rmsArray,N,pulse_samplewidth,startsec,min,max,x);
Run Code Online (Sandbox Code Playgroud)

声明findpeak如下:

int* findpeak(float* data, int n, int pulse_samplewidth,float startsec,float min,float max, float* x);
Run Code Online (Sandbox Code Playgroud)

findpeak函数内部,我将一个特定的值添加data到堆栈中,如下所示:

std::stack<float> peaks_y;
for (int loop1 = 0; loop1 < n; ++loop1) {
if( some condition)
{
peaks_y.push(data[loop1]); // point of error.
}
}
Run Code Online (Sandbox Code Playgroud)

我把它推到堆栈的地方,我在valgrind上得到以下错误

==17917== Invalid read of size 4
==17917==    at 0x4109C2: findpeak(float*, int, int, float, float, float, float*) (stat_utility.C:358)
==17917==    by 0x410778: find_pulses(int, float*, int, int, float) (stat_utility.C:321)
==17917==    by 0x410F46: find_pulses(int, floatcomplex *, int, int, float) (stat_utility.C:426)
==17917==    by 0x403385: main (DetectRFI.C:207)
==17917==  Address 0x18796c20 is 0 bytes after a block of size 8,326,112 alloc'd
==17917==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17917==    by 0x410507: find_pulses(int, float*, int, int, float) (stat_utility.C:285)
==17917==    by 0x410F46: find_pulses(int, floatcomplex *, int, int, float) (stat_utility.C:426)
==17917==    by 0x403385: main (DetectRFI.C:207)
Run Code Online (Sandbox Code Playgroud)

我调试到这一点,我发现我必须在阵列上填充所有值.任何人都可以告诉我错误实际意味着什么?

Mik*_*our 5

你正在阅读超越rmsArray.

那是因为你把它N当作数组大小,当实际大小是N-pulse_samplewidth+1,它小于N假设pulse_samplewidth大于1.