HEAP CORRPUTION DETECTED: after Normal block (#187) - c++

Wrote a simple program. You write a number in the console and an array with the size of the number you wrote in is created and printed. I have now this error, heap corruption detected and I see no problems with my code so please help me out.
#include <iostream>
class dmas
{
public:
int num;
dmas(int size)
{
this->num = size;
}
int* a = new int[num];
void logic()
{
for (int i = 0; i < num; i++)
{
a[i] = rand() % 100;
}
}
void print()
{
for (int i = 0; i < num; i++)
{
std::cout << a[i] << std::endl;
}
delete [] a;
}
};
int main()
{
srand(time(NULL));
int size;
std::cout << "Enter the size of the massive" << std::endl;
std::cin >> size;
dmas a(size);
a.logic();
a.print();
return 0;
}

The problem is this initialization of the pointer a
class dmas
{
public:
int num;
dmas(int size)
{
this->num = size;
}
int* a = new int[num];
//...
The call of the operator new occurs when the variable num is default initialized and has no yet the value of the parameter size assigned to it in the body of the constructor.
At least you need to write
dmas(int size) : num( size )
{
}
Pay attention to that the call of operator delete []
delete [] a;
you should move from the function print to the class destructor.

Let's check the value of num at the allocation.
I added a function
int printNum(int num) {
std::cout << "num = " << num << std::endl;
return num;
}
and changed the allocation
int* a = new int[num];
to
int* a = new int[printNum(num)];
This resulted in num = 0 being printed despite of I entered 10 for the standard input.
Now you can see the value of num set in the constructor is not used here.
To fix this, you can use member initializer:
dmas(int size) : num(size)
{
}

You don't allocate any memory at all, because this int* a = new int[num]; is outside the scope of your constructor!
To make it work, replace this piece of code:
public:
int num;
dmas(int size)
{
this->num = size;
}
int* a = new int[num];
with this:
public:
int num;
int *a;
dmas(int size)
{
this->num = size;
a = new int[num];
}
Then should work fine!

Related

Getting garbage value when trying to get the value from Private Array

I have created a class called Array in which there is a static Array . I have made this Array as private.
class Array
{
private:
int A[10] ;
int size;
int length;
I want to access the value of the elements of this array. For this I have created one get function which would return the values of elements at different positions.
int Array::Get(int x)
{
return A[x];
}
But when I try to print the value of the particular element after inserting elements in array it throws some garbage value.
Full CODE:
#include <iostream>
using namespace std;
class Array
{
private:
int A[10] ;
int size;
int length;
public:
Array()
{
A[10];
size =10;
length = 0;
}
Array(int sz)
{
int A[10];
size = sz;
length = 0;
}
void Display();
void Append(int x);
int Get(int x);
};
int Array::Get(int x)
{
return A[x];
}
void Array::Display ()
{
cout << "\n Elements are\n";
for (int i = 0 ; i < length ; i++)
{
cout<<A[i]<<" ";
}
}
void Array::Append(int x)
{
if(length<size)
A[length++]=x;
}
int main()
{
Array arr1;
int si = 10;
arr1= Array(si);
cout << "enter the elements here" << endl;
int x;
for (int i = 0 ; i < si ; i++)
{
printf("enter the element %d \n " , i);
scanf("%d",&x);
arr1.Append(x);
}
arr1.Display() ;
int count;
count = arr1.Get(0);
printf("%d" , &count);
}
I assume you are a c developer or used to use c.
Thanks guys for pointing out bad lines in your code.
I tried your code in my IDE and fixed it, but I think you need to study more in the classes. I am a beginner but I noticed these mistakes in your code.
First, when you want to create an array of flexible size, you should not give it a fixed size.
As you did in your class member variables:
private:
int A[10] ;
int size;
int length;
You already gave it a size of 10, but in the constructors you created a constructor that tries to resize the array:
Array(int sz)
{
int A[10];
size = sz;
length = 0;
}
Also when you try to get the number x of your array:
int number;
count = arr1.Get(0);
printf("%d" , &count);
You are specifying the address of the variable count, not its value.
Here is your fixed code :
#include <iostream>
using namespace std;
class Array {
private:
int *A;
int size;
int length;
public:
Array() {
// default constructor
A = new int[10];
size = 10;
length = 0;
}
Array(int sz) {
// change the size of array
size = sz;
A = new int[sz];
length = 0;
}
~Array(){
delete [] A;
}
void Display();
void Append(int x);
int Get(int x);
};
int Array::Get(int x) {
if (x < length)
return A[x];
else {
std::cerr << "number is out of rang\n\a";
return 0;
}
}
void Array::Display() {
cout << "\n Elements are\n";
for (int i = 0; i < length; i++) {
cout << A[i] << " ";
}
}
void Array::Append(int x) {
if (length < size)
A[length++] = x;
}
int main() {
int si;
// changing size
// int newsize;
// std::cout << "enter size of your array : ";
// std::cin >> newsize;
// si = newsize;
// Array arr2(newsize);
// default constructor with size 10
Array arr1;
si = 10;
// no need to this
// arr1= Array(si);
cout << "enter the elements here" << endl;
int x;
for (int i = 0; i < si; i++) {
std::cout << "enter number " << i + 1 << " : ";
std::cin >> x;
arr1.Append(x);
}
arr1.Display();
int chose;
std::cout << "enter number to find in array : ";
std::cin >> chose;
int num = arr1.Get(chose);
// if chose is not out of array range
if (num)
std::cout << "number " << chose << " in array is : " << num << '\n';
}

Why my C++ programme has stopped working?

I wrote C++ programme in vs code and When I run it, it ask me to enter the element value but when I enter the second time, it has stopped working. I don't know what the problem is but if you know the please help me to resolve the problem.
#include <iostream>
using namespace std;
class myArray {
public:
int total_size;
int used_size;
int* ptr;
myArray(int tsize, int usize)
{
total_size = tsize;
used_size = usize;
ptr = new int(tsize);
}
myArray() {}
void setvalue()
{
int n;
for (int i = 0; i < used_size; i++) {
cout << "Enter the element" << endl;
cin >> n;
ptr[i] = n;
}
}
void show()
{
for (int i = 0; i < used_size; i++) {
cout << "The element in array" << endl;
cout << ptr[i] << endl;
}
}
};
int main()
{
myArray(10, 2);
myArray a;
a.setvalue();
a.show();
return 0;
}
You used used_size and ptr without initializing them in a.setvalue(); and a.show();.
It seems
myArray(10, 2);
myArray a;
should be
myArray a(10, 2);
Also, as #Yksisarvinen points out,
ptr = new int(tsize);
should be
ptr = new int[tsize];
to allocate an array instead of single int.

Solving Segmentation Fault(core dumping) error

This program doubles the every second integer for the account number given and if the number is greater than 10 it is subtracted by 9. Then output whether the number entered is correct or not. Assuming that the account number is off 5 numbers. I wrote this program but does not get the answer for few number but got a correct answer for other number. Thanks for hint.
#include <iostream>
class AccountNumber {
private:
int size = 5;
int *p;
public:
AccountNumber() { int *p = new (std::nothrow) int[size]; }
~AccountNumber() { delete[] p; }
void getaccount() {
int acc;
std::cout << "Enter the account number: ";
std::cin >> acc;
for (int i = 0; i < size; i++) {
p[i] = acc % 10;
}
setaccount(p);
}
void setaccount(int a[]) {
for (int i = 0; i < size; i++) {
p[i] = a[i];
}
}
void doubles() {
AccountNumber at;
at.p = new int[size];
at.p = p;
for (int i = 0; i < size; i++) {
if (i % 2 == 1) {
at.p[i] = at.p[i] * 2;
if (at.p[i] > 10) {
at.p[i] = at.p[i] - 9;
}
}
}
p = at.p;
}
bool sum() {
bool ot;
int sum = 0;
for (int i = 0; i < size; i++) {
sum = sum + p[i];
}
int mod = sum % 10;
if (mod == 0) {
ot = true;
} else {
ot = false;
}
return ot;
}
void display(std::ostream &outs) {
bool ot = sum();
doubles();
outs << "Account number entered is ";
if (ot) {
outs << " correct.\n";
} else {
outs << " is not correct. \n";
}
}
};
int main(int argc, char const *argv[]) {
AccountNumber accn;
accn.getaccount();
accn.display(std::cout);
return 0;
}
Output
Enter the account number: 35556
Segmentation fault (core dumped)
I don't know where I'm going wrong.
The issue here is that you never allocate p. Look at your constructor:
AccountNumber()
{
int *p = new(std::nothrow) int[size];
}
Here you are defining a new pointer variable p, which will be used instead of the member pointer variable p you defined in the private fields. What happens here is that you are allocating an int array for a new variable p, but that variable p gets thrown out at the end of the constructor (and also causes a memory leak because of the dynamic allocation that will never be reclaimed).
What you should do here instead is simply assigning the new allocated array to the member pointer variable p without redefining it, ie.
AccountNumber() {
p = new (std::nothrow) int[size];
}
And to prevent such mistakes from happening again, you should consider using a specific naming convention for class members, such as m_ prefix (for example)
class AccountNumber {
private:
int m_size = 5;
int *m_p;
public:
AccountNumber() {
m_p = new (std::nothrow) int[size];
}
};

Write a dynamic array

I want to write a program that can use a dynamic array.
A size is to be passed via the constructor and as soon as this size is reached, a new array is generated in which the previous values are copied into it.
For this, I overloaded the [] operator. The program seems to work at first glance.
But after I tried to implement an array with the size 100 and to save 20000 elements here, different numbers are output.
At the first run, more than 7000 numbers were displayed. After another run over 1800. However, never the desired 20000.
What could be the reason for this?
#include <iostream>
using namespace std;
template<class T>
class Container{
public:
T *dynamicArray;
private:
T *newArray;
int size;
public:
Container(int size){
this->size=size;
dynamicArray=new T[size];
}
T operator[] (unsigned long index){
if(index>size-1){
newArray=new T[size+(index-size)];
T i;
for(i=0; i<(size+(index-size)); i++){
newArray[i]=dynamicArray[i];
}
delete[] dynamicArray;
dynamicArray=newArray;
delete[] newArray;
}
return dynamicArray[index];
}
};
int main()
{
Container <int> dArray(100);
for(int i=1; i<20000; i++){
dArray.dynamicArray[i]=i;
cout << dArray.dynamicArray[i] << "\n";
}
return 0;
}
Thank you!
first , this code didn't call the overloaded [] operator function , its just using default operator [] of type T array , and it never allocate any memory , you can output at allocate memory position
dArray.dynamischesArray[i]=i;
cout << dArray.dynamischesArray[i] << "\n";
and there it some error logic in the overloaded [] operator function
T operator[] (unsigned long index){
if(index>size-1){
neuesArray=new T[size+(index-size)];
T i;
for(i=0; i<(size+(index-size)); i++){
neuesArray[i]=dynamischesArray[i];
}
delete[] dynamischesArray;
dynamischesArray=neuesArray;
//delete[] neuesArray; cannot deleted ,course error
size = index + 1; //keep size sync real size
}
return dynamischesArray[index];
}
this is modified code can be run correct :
#include <iostream>
#include <string>
using namespace std;
template<class T>
class Container {
public:
T *dynamischesArray;
private:
T *neuesArray;
int size;
public:
Container(int size) {
this->size = size;
dynamischesArray = new T[size];
}
T& operator[] (unsigned long index) {
if (index > size - 1) {
cout << "allocate :" << index<<"\n";
neuesArray = new T[index+1];
unsigned long i;
for (i = 0; i < size; i++) {
neuesArray[i] = dynamischesArray[i];
}
delete[] dynamischesArray;
dynamischesArray = neuesArray;
//delete[] neuesArray;
size = index+1;
}
T&ret = dynamischesArray[index];
//return dynamischesArray[index];
return ret;
}
};
int main()
{
Container <int> dArray(100);
for (int i = 1; i < 20000; i++) {
dArray[i] = i;
cout <<"i="<<i<<" "<< dArray[i] << "\n";
//dArray.dynamischesArray[i] = i;
//cout << dArray.dynamischesArray[i] << "\n";
}
return 0;
}
this is result

Code runs when in main() but gives error when in function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am writing a dynamic matrix class that stores each non-zero value as a List of 3 elements [row,column,value]
I made a dynamic array class called "List", and class"Matrix" a List of list pointers.
My code to transpose the Matrix works:
void transpose(Matrix tripleList)
{
for (int i = 0; i < tripleList.getNumOfElem(); i++)
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
cout << "\n";
}
}
it works when written directly in main() but gives error when in stand alone function. can anyone explains why and how to fix it?
Full code:
#include <iostream>
using namespace std;
class List //a dynamic int pointer array
{
private:
int capacity;
int numOfElem;
int *arr;
//initialize all values in capacity to 0
void initialize(int from)
{
for (int i = from; i < capacity; i++)
{
arr[i] = 0;
}
}
//double the capaicty, then initialize
void expand()
{
capacity *= 2;
int *tempArr = new int[capacity];
for (int i = 0; i < numOfElem; i++)
tempArr[i] = arr[i];
delete[] arr;
arr = tempArr;
initialize(numOfElem);
}
public:
List()//constructor
{
capacity = 10;
numOfElem = 0;
arr = new int[capacity];
}
~List()//destrcutor
{
delete[] arr;
}
//add int to the end of List
void append(int newElement)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = newElement;
}
//Copy all element of an input list to the end of List
void copy(List list)
{
for (int i = 0; i < list.getNumOfElem(); i++)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = list.getAt(i);
}
}
//get reference of the int at an index in te list
int* getAddress(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return &arr[index];
}
//change the value of at specific index
void set(int index, int value)
{
arr[index] = value;
}
//get int at an index in te list
int getAt(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return arr[index];
}
int getNumOfElem()
{
return numOfElem;
}
void displayList()
{
for (int i = 0; i < numOfElem; i++)
{
cout << arr[i] << " ";
}
}
};
class Matrix //a List of list pointers
{
private:
int capacity;
int numOfElem;
List* *arr;
void initialize(int from)
{
for (int i = from; i < capacity; i++)
{
arr[i] = new List;
}
}
void expand()
{
capacity *= 2;
List* *tempArr = new List*[capacity];
for (int i = 0; i < numOfElem; i++)
tempArr[i] = arr[i];
delete[] arr;
arr = tempArr;
initialize(numOfElem);
}
public:
Matrix()
{
capacity = 10;
numOfElem = 0;
arr = new List*[capacity];
}
~Matrix()
{
delete[] arr;
}
void append(List* newElement)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = newElement;
}
void set(int index, List* value)
{
arr[index] = value;
}
List* getAt(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return arr[index];
}
int getNumOfElem()
{
return numOfElem;
}
};
void transpose(Matrix tripleList)
{
for (int i = 0; i < tripleList.getNumOfElem(); i++)
{
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
cout << "\n";
}
}
int main()
{
int m, n, input;
cout << "Please enter the number of rows and columns of the matrix :\n";
cin >> m >> n;
Matrix tripleListMatrix;
int k = 0;
cout << "Please enter the matrix : \n";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> input;
if (input != 0)
{
tripleListMatrix.append(new List);
(*(tripleListMatrix.getAt(k))).append(i + 1);
(*(tripleListMatrix.getAt(k))).append(j + 1);
(*(tripleListMatrix.getAt(k))).append(input);
k++;
}
}
}
cout << "The triple list of matrix is:\n";
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
(*(tripleListMatrix.getAt(i))).displayList();
cout << "\n";
}
cout << "\n\n";
//transpose(tripleListMatrix);
//the code below is the same as in the function transpose but transpose gives error
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
//cout << "\t" << list;
cout << "\n";
}
cout << "\n\n";
//checking that tripleListMatrix is unchanged
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
(*(tripleListMatrix.getAt(i))).displayList();
cout << "\n";
}
return 0;
}
List* *arr;
When you call transpose(), it makes a copy Matrix because you're not passing by reference. That copy just has a copy of the address for your List, not it's own List object. When the destructor runs on the copy, it clears up the allocated memory, but the original Matrix object in main still points to that same memory. When that object goes away, its destructor tries to free the same memory again and that's bad.
You probably meant:
void transpose(Matrix const & tripleList)
So that no copy is made when calling transpose(), but you should also explicitly delete the copy construtor of Matrix so it cannot be called
Matrix(Matrix const &) = delete;
or make an explicit Matrix copy constructor that makes a deep copy of the memory.