I am writing a function to find peak in an array in a given range. I don't know the exact number of peaks in the given array. So I am using Dynamic memory allocation to store the peaks. The problem I am facing is that ,
int *findPeak(float *pArray, int length, int window, int *pCount) {
int i, j ,count = 0, toPositive = 0, toNegative = 0;
float peak;
int *pPeakBuffer;
bool firstZeroCross = false, toPositivePeak = false;
int *peakBuffer = (int*)malloc(1*sizeof(int));
for (i = 0; i < length; i += window) {
if (count == 0) {
peak = 0.0;
for (j = i; j < window; j++) {
if (peak < pArray[j]) {
peak = pArray[j];
peakBuffer[count] = j;
}
}
printf("Peak = %d\n\r", peakBuffer[count]);
count++;
}
else {
peak = 0.0;
peakBuffer = (int*)realloc(peakBuffer, 1*sizeof(int));
for (j = i; j < i+window; j++) {
if (peak < pArray[j]) {
peak = pArray[j];
peakBuffer[count] = j;
}
}
printf("Peak = %d\n\r", peakBuffer[count]);
count++;
}
}
*pCount = count;
printf("count = %d\n\r", count);
for (i = 0; i < count; i++)
printf("%d ,", peakBuffer[i]);
printf("\n\r");
return peakBuffer;
}
when a peak value is detected and it store it in the first memory. When the 2nd peak is detected it store in the 2nd memory, then the value in the first memory(previous memory) is changed to zero or other numbers and so on. Only the first and last peak is obtained. rest of the memory store some unknown values(not the peak value). I don't know why it is happening.