Can't find memory leak - c++

I am learning C++ and my instructor has us going over dynamic memory allocation. In the below code it seems I have a memory leak because when I run the program I must about it at the end.
In the output I get everything is correct except for the Data: field which should list all the numbers in the array, but instead gives me some -3435893 jibberish.
Lowest: also does this. After the program displays everything I get a memory error that memory is being written to after end of heap buffer.
I'm new to all this but I'm guessing the problem is when arrPTR[0] is accessed just because I get the same problem for Lowest: and not Highest:. I don't know for sure but I would appreciate any help I can get.
#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;
}

The first thing I spot is that in sortArray you access element count + 1 which can be one-past the end of your array. After that, all other bets about your program behavior are off.

Related

Extract pair numbers from array

Good evening, folks.
I'm currently experiencing difficulties with extracting pair numbers from an array. I have the following code:
#include <iostream>
using namespace std;
int *paire(int *d, int length) {
int counter = 0;
int position = 0;
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0)
counter++;
}
int *k = new int[counter];
for (int i=0; i<length; i++) {
if (d[i] % 2 ==0) {
k[position] = d[i];
position++;
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int *array1 = paire(b,8);
for (int i=0; i<5; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i];
}
delete[] array1;
return 0;
}
So I think I've got it right with initializing the new array in function paire, but I'm having difficulties to iterate through the array.
P.S. I'm first year in university, so I would really be thankful if you can keep the same simplicity in the answers. Thanks in advance!
It appears that you need to return 2 separate values: the number of even numbers in the array b, and the address of the newly allocated memory that is storing exclusively those even numbers.
Since you can not return multiple variables, one solution that does minimal modification to your code would be as follows.
int *paire(int *d, int length, int& counter) {
counter = 0;
// rest of your function remains unchanged
// ...
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int evenNumbers;
int *array1 = paire(b,8, evenNumbers);
for (int i=0; i<evenNumbers; i++) {
cout<<array1[i];
}
delete [] array1;
return 0;
}
Alternatively, you can return the value in counter and send the reference to the int* variable as an argument to paire function. Or, you can declare paire to have return type void and use references to pass back both the values.
You can further simplify your function by allocating to that of the length and returning the counter by an output parameter.
#include <iostream>
using namespace std;
int *paire(int *d, int length, int &counter) {
counter = 0;
int *k = new int[length]; // allocate for the maximum memory
for (int i = 0; i < length; ++i) {
if (d[i] % 2 == 0) {
k[counter++] = d[i];
}
}
return k;
}
int main() {
int b[8] = {1,2,3,4,5,6,7,8};
int counter = 0;
int *array1 = paire(b,8, counter);
for (int i=0; i<counter; i++) { // how can I point here to the counter in paire() ?
cout<<array1[i] << " ";
}
delete [] array1;
return 0;
}
But please note that as others have already pointed out this method is quite error prone in the sense that it leaves the responsibility to the client to delete the internal memory used by paire function.

Member Class Functions

So I am trying to figure out how to create a function that Returns an Array of all integers that are in common with self and ary and returns an empty Array if there are no intersections. This is what I have so far:
IntArray* findIntersections(IntArray &ary) {
int length1 = ary.getLength(); // Getting the length of &ary.
int length2 = getLength([//Right here, there's something to do with "this" because I've created a mArray already and defined it, but I'm not sure how to re-call it here.]); // Getting the length of self.
int length4 = 0; // Because anarchy
if (length1 > length2){ // An if statement to match length4 with the longest array.
length4 = length2;
} else {
length4 = length1;
}
IntArray* newArray; // New IntArray on the heap.
newArray = new* int[length4];
int k = 0;
for (int j = 0; j < length1; j++){ // Two for loops getting the iterator on the same page.
for (int i = 0; i < length2; i++){
if (ary.get(j) == [//The this from earlier, whatever it is][i]){ // Checking to see if digits match each other.
newArray[k] = (ary[j]); // Writing the digit into the NewArray.
k++; // Adding one to the k count to progress the the iterator.
}
}
}
return newArray;
}
In the end, there I know there's gonna be three arrays. The one being passed in, the one being created and passing out, and then that this reference which I honestly don't even know what it is. I'm thinking it's an mArray I created earlier, but I'm not exactly sure. Any help on this would be absolutely fantastic!
Also, here's my .hpp file:
class IntArray {
private:
int *mArray;
int mSize;
public:
IntArray(int *array, int size);
int get(int index);
int getLength();
int indexOf(int value);
bool remove(int index);
IntArray* findIntersections(IntArray &ary);
bool isSubsequence(IntArray &ary);
~IntArray();
};
And my .cpp file:
#include "IntArray.hpp"
IntArray::IntArray(int *array, int size) {
int *newArray = new int [size];
for (int i = 0; i < size; i++){
newArray[i] = array[i];
}
}
int IntArray::get(int index) {
return mArray[index];
}
IntArray::~IntArray() {
delete[] mArray;
}
int IntArray::getLength() {
return mSize;
}
int getLength(int *array){
int length = (sizeof(array)/sizeof(array[0]));
return length;
}
int indexOf(int *array, int value){
int length = getLength(array);
for (int i = 0; i < length; i++){
if (value == array[i]){
return i;
}
}
return -1;
}
bool remove(int *array, int index){
int length = getLength(array);
if (0 <= index && index < length){
for (int i = index + 1; i < length; ++i){
array[i - 1] = array[i];
}
for (int i = 0; i < length; i++)
return true;
} else {
return false;
}
}
IntArray* findIntersections(IntArray &ary) {
int length1 = ary.getLength(); // Getting the length of &ary.
int length2 = getLength([//Right here, there's something to do with "this" because I've created a mArray already and defined it, but I'm not sure how to re-call it here.]); // Getting the length of self.
int length4 = 0; // Because anarchy
if (length1 > length2){ // An if statement to match length4 with the longest array.
length4 = length2;
} else {
length4 = length1;
}
IntArray* newArray; // New IntArray on the heap.
newArray = new* int[length4];
int k = 0;
for (int j = 0; j < length1; j++){ // Two for loops getting the iterator on the same page.
for (int i = 0; i < length2; i++){
if (ary.get(j) == [//The this from earlier, whatever it is][i]){ // Checking to see if digits match each other.
newArray[k] = (ary[j]); // Writing the digit into the NewArray.
k++; // Adding one to the k count to progress the the iterator.
}
}
}
return newArray;
}
bool isSubsequence(int *array) {
int length = getLength(array);
for (int i = 0; i < length - 1; i++) {
if (array[i] != array[i + 1])
return false;
}
return true;
}
Your implementation of findIntersection is not defined as a member function, you have defined it as a global function. The member function declaration named findIntersection is not defined. In short: you forgot IntArray:: before the function name

C++ Program To Find Smallest and Largest Number In Array

Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001

Bubble sorting random numbers

I am trying to use bubble sort to sort a set of random numbers. But my code results in a messed up order. For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated. Below is my code.
#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);
int main()
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE];
for (int count = 0; count < MAX_VALUE; count++)
{
numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
cout << numbers[count]<< endl;
sortArray(numbers, count);
showArray(numbers, count);
}
}
void sortArray(int numbers[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size -1); count++)
{
if (numbers[count] > numbers[count + 1])
{
temp = numbers[count+1];
numbers[count+1] = numbers[count];
numbers[count] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int numbers[], int size)
{
for (int count = 0; count < size; count++)
cout <<numbers[count] << endl;
}
Thanks
The sorting code is correct.
The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.
You should first fill all the data, then sort, then display the sorted result.

how to display and do calculations with floats using c++ dinamic memory

how can I make it say maximum value 5.3 instead of just 5 and also
make it work with the other values and methods??
//main class
#include<iostream>
#include "FloatList.h"
using namespace std;
int main(){
int size;
float element;
cout<<"Enter the maximum number of values to store in the array: ";
cin>>size;
FloatList f1(size);
for(int e=0;e<size;e++){
cout<<"Enter the value you want to store in the position number "<<e+1<<" :";
cin>>element;
f1.setElement(e,element);
}
cout<<endl;
cout<<"The elements in the array are the following: "<<endl;
for(int i=0;i<size;i++){
cout<<f1.getElement(i)<<endl;
}
cout<<"The maximum value in the array is: "<<f1.calculateMaxValue()<<endl;
cout<<"The minimum value in the array is: "<<f1.calculateMinValue()<<endl;
cout<<"The average value in the array is: "<<f1.calculateAverage()<<endl;
cout<<"This is now a copy of the original array:"<<endl;
return 0;
}
//FloatList.h
#ifndef FLOATLIST_H_
#define FLOATLIST_H_
#include<iostream>
#include <cstdlib>
using namespace std;
class FloatList {
private:
int size;
int numElements;
float *list;
bool isValid(int);
public:
FloatList(int=1);
FloatList(FloatList &);
void setElement(int, int); // Sets an element to a value.
float getElement(int); // Returns an element.
~FloatList();
void setNumElements(int numElements);
void setSize(int size);
int getNumElements();
int getSize();
float calculateMaxValue();
float calculateMinValue();
float calculateAverage();
};
#endif /* FLOATLIST_H_ */
//FloatList.cpp
#include "FloatList.h"
FloatList::FloatList(int tempSize):size(tempSize){
list = new float[size];
numElements = size;
for (int i = 0; i < size; i++){
list[i] = 0;
}
}
void FloatList::setNumElements(int numElements) {
this->numElements = numElements;
}
FloatList::FloatList(FloatList& temp) {
size=temp.getSize();
list = new float[size];
numElements = size;
for (int i = 0; i < size; i++){
list[i] = temp.getElement(i);
}
}
int FloatList::getNumElements() {
return numElements;
}
int FloatList::getSize() {
return size;
}
void FloatList::setSize(int size) {
this->size = size;
}
FloatList::~FloatList() {
delete [] list;
}
bool FloatList::isValid(int element)
{
bool status;
if (element < 0 || element >= numElements)
status = false;
else
status = true;
return status;
}
void FloatList::setElement(int element, int value)
{
if (isValid(element))
list[element] = value;
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
float FloatList::getElement(int element)
{
if (isValid(element))
return list[element];
else
{
cout << "Error: Invalid subscript\n";
exit(EXIT_FAILURE);
}
}
float FloatList::calculateMaxValue() {
float maxValue=list[0];
for(int i=1;i<size;i++){
if(list[i]>maxValue){
maxValue=list[i];
}
}
return maxValue;
}
float FloatList::calculateMinValue() {
float minValue=list[0];
for(int i=1;i<size;i++){
if(list[i]<minValue){
minValue=list[i];
}
}
return minValue;
}
float FloatList::calculateAverage() {
float average;
for(int i=0;i<size;i++){
average+=list[i];
}
return average/size;
}
//output:
Enter the maximum number of values to store in the array: 3
Enter the value you want to store in the position number 1 :1.2
Enter the value you want to store in the position number 2 :5.3
Enter the value you want to store in the position number 3 :4.5
The elements in the array are the following:
1
5
4
The maximum value in the array is: 5
The minimum value in the array is: 1
The average value in the array is: 3.33333
This is now a copy of the original array:
1
5
4
how can I make it say maximum value 5.3 instead of just 5 and also
make it work with the other values and methods??`