[英]Can't find memory leak
我正在學習C ++,我的老師讓我們研究了動態內存分配。 在下面的代碼中,似乎有內存泄漏,因為在運行程序時,我必須在結尾處進行處理。
在輸出中,我得到的所有信息都是正確的,但Data:
字段應列出數組中的所有數字,但給了我一些-3435893
胡言亂語。
Lowest:
也這樣做。 程序顯示所有內容后,我收到一個內存錯誤,即在堆緩沖區結束后正在寫入內存。
我不熟悉所有這些,但是我想問題是訪問arrPTR [0]時僅僅是因為我遇到了Lowest:
而不是Highest:
的相同問題。 我不確定,但我將不勝感激。
#include <iostream>
using namespace std;
int* readArray(int&);
void sortArray(int *, const int * );
int findMode(int*, const int *);
double averageNumber(int*,const int*);
void lowestHighest(int*,const int*,int&,int&);
void printFunc(int*,const int*, int, int, double);
int main ()
{
int size = 0;
int *arrPTR = readArray(size);
const int *sizePTR = &size;
sortArray(arrPTR, sizePTR);
int mode = findMode(arrPTR,sizePTR);
double average = averageNumber(arrPTR, sizePTR);
int lowest = 0, highest = 0;
lowestHighest(arrPTR,sizePTR,lowest,highest);
printFunc(arrPTR,sizePTR,lowest,highest,average);
delete [] arrPTR;
system("pause");
return 0;
}
int* readArray(int &size)
{
cout<<"Enter a number for size of array.\n";
cin>>size;
int *arrPTR = new int[size];
for(int count = 0; count < size; count++)
{
cout<<"Enter positive numbers to completely fill the array.\n";
cin>>arrPTR[count];
}
return arrPTR;
}
void sortArray(int *arrPTR, const int *sizePTR)
{
int temp;
bool swap;
do
{
swap = false;
for(int count = 0; count < *sizePTR; count++)
{
if(arrPTR[count] > arrPTR[count+1])
{
temp = arrPTR[count];
arrPTR[count] = arrPTR[count+1];
arrPTR[count+1] = temp;
swap = true;
}
}
} while (swap);
}
int findMode(int *arrPTR, const int *sizePTR)
{
int most_found_element = arrPTR[0];
int most_found_element_count = 0;
int current_element = arrPTR[0];
int current_element_count = 0;
int count;
for (count = 0; count < *sizePTR; count++)
{
if(count == arrPTR[count])
current_element_count++;
else if(current_element_count > most_found_element)
{
most_found_element = current_element;
most_found_element_count = current_element_count;
}
current_element = count;
current_element_count=1;
}
return most_found_element;
}
double averageNumber(int *arrPTR,const int *sizePTR)
{
double total = 0;
for (int count = 0; count > *sizePTR; count++)
total+=arrPTR[count];
double average = total / *sizePTR;
return average;
}
void lowestHighest(int *arrPTR, const int *sizePTR,int &lowest, int &highest)
{
//Since array is already sorted the lowest number will be in the lowest element and the highest will be in the highest element.
lowest = arrPTR[0];
highest = arrPTR[*sizePTR-1];
}
void printFunc(int *arrPTR, const int *sizePTR, int lowest, int highest, double average)
{
cout<<"Array Stats\n";
cout<<"Data:";
for(int count = 0; count < *sizePTR; count++)
cout<<arrPTR[count];
cout<<"\n";
cout<<"Mode:"<<endl;
cout<<"Average:"<<average<<endl;
cout<<"Low Value:"<<lowest<<endl;
cout<<"High Value:"<<highest<<endl;
}
我發現的第一件事是,在sortArray
您可以訪問元素count + 1
,這可以是數組末尾的最后一位。 之后,關於程序行為的所有其他押注都將關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.