Vivek V K
Vivek V K

Reputation: 1128

Valgrind error -Address is zero bytes after allocation - C/C++

I am valgrinding my project for a memory leak. I am getting an error for which I cant understand the root cause of it. My code is huge so I will put chunks here that are needed.

Basically I have an array in a function called find_pulses that I dynamically allocate like this:

float*rmsArray;
    rmsArray = (float*)malloc((N-pulse_samplewidth+1)*sizeof(float));

I debugged to this point and found that N-pulse_samplewidth+1 is non zero. (its actually ~ 2^21)

I populate the values to this array like this:

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

I send this array to another function called findpeak like this:

 int* ans = findpeak(rmsArray,N,pulse_samplewidth,startsec,min,max,x);

declaration of findpeak goes like this:

int* findpeak(float* data, int n, int pulse_samplewidth,float startsec,float min,float max, float* x);

inside the findpeak function, I add a particular value from data to a stack like this:

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

The place where I push it on stack, I get the following error on 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)

I debugged to this point and I found I had all the values populated on the array as necessary. Can anyone tell me what the error actually means??

Upvotes: 0

Views: 853

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254691

You're reading beyond the end of rmsArray.

That's because you treat N as the array size, when the actual size isN-pulse_samplewidth+1, which is less than N assuming pulse_samplewidth is greater than 1.

Upvotes: 5

Related Questions