Why my C++ programme has stopped working? - c++

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.

Related

HEAP CORRPUTION DETECTED: after Normal block (#187)

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!

Problem using std::sort with custom class

Doing hackerrank problem "Attending Workshops" https://www.hackerrank.com/challenges/attending-workshops/problem
I have the problem that I can't sort my vector. I tried with a lambda (in commentary) and then by overloading the operator >.
My vector never turn out to be sorted. Can you help me find what I did wrong. Here is my code:
#include<bits/stdc++.h>
using namespace std;
//*************ABOVE IS LOCKED CODE BY HACKERRANK****************;
//Define the structs Workshops and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop
{
int startTime;
int endTime;
int duration;
Workshop(){}
Workshop(int pStartTime, int pDuration)
:startTime(pStartTime), duration(pDuration)
{
endTime = startTime + duration;
}
bool operator < (const Workshop &other) const
{
cout << "trace inside operator never showing up" << endl;
return endTime < other.endTime;
}
};
struct Available_Workshops
{
int nbWorkshop;
vector<Workshop> workshops;
Available_Workshops(int *start_times, int *durations, int n)
:nbWorkshop(n)
{
workshops.reserve(n);
for(int i = 0; i < n; ++i)
{
workshops[i] = Workshop(start_times[i], durations[i]);
}
}
};
Available_Workshops *initialize(int *start_time, int *duration, int n)
{
return new Available_Workshops(start_time, duration, n);
}
int CalculateMaxWorkshops(Available_Workshops *avai_work_ptr)
{
//The two for loops are just there to trace the content of avai_work_ptr->nbWorkshop to validate sorting...
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
std::sort(avai_work_ptr->workshops.begin(), avai_work_ptr->workshops.end());//, [](const Workshop &a, const Workshop &b){cout << "compar"; return a.startTime < b.startTime;});
for(int i = 0; i < avai_work_ptr->nbWorkshop; ++i)
cout << avai_work_ptr->workshops[i].startTime << " " << avai_work_ptr->workshops[i].endTime << endl;
int maxWorkshop = 0;
//Chunk of code removed because it is not related to the sort problem...
//...
return maxWorkshop;
}
//*************BELOW IS LOCKED CODE BY HACKERRANK****************;
int main(int argc, char *argv[]) {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
Thank you.
workshops.reserve(n);
is wrong. It just do allocation and not inclease the number of valid elements, so the end() iterator will still be the top of the array.
You should use
workshops.resize(n);
instead.

What are the rules for function returning pointer in c++ did I miss something in my code?

I want to create a function which generates an array(filled with random numbers) of the size I give as an input and the function returns the address of the first element of the generated array. I wrote the code as best as possible without any errors or warning. But at the runtime, the program crashes. I try to debug it but the debugger also froze and do nothing. I think the problem is in returning the pointer. Please help.
#include<iostream>
#include<cstdlib>
using namespace std;
int** the_gen(int num)
{
srand(1000);
int *ptr= new int(num);
int** const dptr=&ptr;
for(int i=0;i<num;i++)
{
*ptr= rand();
ptr++;
}
return dptr;
}
int main()
{
cout<<"Size of array:"<<endl;
int size_of_array;
cin>>size_of_array;
int **a;
a=the_gen(size_of_array);
for(int i=0;i<size_of_array;i++)
{
cout<<**a<<",";
a++;
}
}
you were using int** unnecessarily. only need to use that if you're creating an array of int pointers or a 2d array of int's:
the following code does what you're after i think:
#include<iostream>
#include<cstdlib>
using namespace std;
int* the_gen(int num)
{
srand(1000);
//edit
int *ptr = new int[num];
int* const dptr = ptr;
for (int i = 0; i < num; i++)
{
*ptr = rand();
ptr++;
}
return dptr;
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
a = the_gen(size_of_array);
for (int i = 0; i < size_of_array; i++)
{
cout << *a << ",";
a++;
}
}
I think returning pointer is always bad idea, we should take memory pointers as a parameter as the follow
void the_gen(int num, int** arry)
{
srand(1000);
int *ptr = new int[num];
*arry = ptr;
for (int i = 0; i < num; i++)
{
ptr[i] = rand();
}
}
int main()
{
cout << "Size of array:" << endl;
int size_of_array;
cin >> size_of_array;
int *a;
the_gen(size_of_array, &a);
for (int i = 0; i < size_of_array; i++)
{
cout << a[i] << ",";
}
}

Dynamically allocated

I need help, to change the size and arr, in the main function to allocate memory dynamically (dynamically allocated)
this program uses looping for integer numbers for the 1st program, while classes and structs are the second program
program_1
#include <iostream>
#include <iterator>
using namespace std;
void display_desc(const int arr[], int size)
{
int copy_arr[size];
copy(arr, arr + size, copy_arr);
int temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (copy_arr[i] > copy_arr[j]) {
temp = copy_arr[i];
copy_arr[i] = copy_arr[j];
copy_arr[j] = temp;
}
}
}
for (int i = 0; i < size; i++) {
cout << copy_arr[i] << " ";
}
cout << endl;
}
int main()
{
int size = 5;
int arr[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
display_desc(arr, size);
}
and
program_2
Change the variable that is in int main () to use dynamic memory allocation
#include <iostream>
#include <iterator>
#include <windows.h>
using namespace std;
const int SLOT_ROOM = 5;
class Person {
public:
Person()
{
name = "";
}
Person(string names)
{
name = names;
}
void set_name(string names) { name = names; }
string get_name() { return name; }
private:
string name;
};
struct Slot {
bool blank;
Person person;
};
class rental {
public:
Slot used[SLOT_ROOM];
rental()
{
for (int i = 0; i < SLOT_ROOM; i++) {
Person person;
used[i].person = person;
used[i].blank = true;
}
}
int in(const Person person)
{
for (int i = 0; i < SLOT_ROOM; i++) {
if (used[i].blank) {
used[i].blank = false;
used[i].person = person;
cout << "used in position " << i << endl;
return i;
}
}
cout << "the rental is full" << endl;
return -1;
}
bool out(int i)
{
used[i].blank = true;
}
Slot* get_rental_list()
{
return used;
}
void print_person_list()
{
cout << endl
<< "List rental" << endl;
for (int i = 0; i < SLOT_ROOM; i++) {
cout << "Slot rental to " << i << endl;
cout << "Name: " << used[i].person.get_name() << endl;
cout << "Avail: " << used[i].blank << endl
<< endl;
}
}
private:
int SLOT_ROOM = 2;
string time_rental;
};
int main()
{
rental rental;
Person person_1("make");
Person person_2("angel");
rental.in(person_1);
rental.in(person_2);
rental.print_person_list();
rental.out(2);
rental.print_person_list();
rental.in(person_2);
rental.print_person_list();
}
please help, I don't understand about using dynamic memory allocation
I still learn c ++
Change
int arr[size];
to
int* arr = new int[size];
You need to make the same change to int copy_arr[size]; in display_desc.
You also need to delete[] memory once you've finished with it.
delete[] arr;
at the end of main, and delete[] copy_arr; at the end of display_desc.
In the second question it's harder to understand what you want. Why do you want to use dynamic allocation? Your code looks perfectly good as it is. You also don't say which variable it is that you want to use dynamic allocation.

C++ allocating memory

Can someone explain me why when i back form function i lost my data from tabOfOffsets. I did the same thing twice and program crash only with the second array.
I printed values of this array on the end of function and everything is clear and correct. Maybe i make mistake somewhere with delete?
Below it is the code.
#include<iostream>
#include <algorithm>
using std::cout;
using std::endl;
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize) {
int temp = std::min(oldSize, newSize);
int *newTabOfValues = new int [newSize] {0};
int *newTabOfOffsets = new int [newSize] {0};
for (int i = 0; i < temp; i++) {
newTabOfValues[i] = tabValue[i];
newTabOfOffsets[i] = tabOffsets[i];
}
delete[] tabValue;
delete[] tabOffsets;
tabValue = new int [newSize] {0};
tabOffsets = new int [newSize] {0};
for (int i = 0; i < newSize; i++) {
tabValue[i] = newTabOfValues[i];
tabOffsets[i] = newTabOfOffsets[i];
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
oldSize = newSize;
delete[] newTabOfValues;
delete[] newTabOfOffsets;
for (int i = 0; i < newSize; i++) {
std::cout << tabOffsets[i] << tabValue[i] << endl;
}
}
int main() {
int SIZE = 10;
int * tabOfOffsets = new int[SIZE];
int * tabOfValues = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
tabOfValues[i] = i;
tabOfOffsets[i] = i;
cout << tabOfValues[i] << " : " << tabOfOffsets[i] << endl;
}
changeSizeOfVector(tabOfValues, tabOfOffsets, SIZE, 12);
for (int i = 0; i < SIZE; i++) {
cout << tabOfOffsets[i] << " : " << tabOfValues[i] << endl;
}
delete[] tabOfOffsets;
delete[] tabOfValues;
}
This function declaration is wrong:
void changeSizeOfVector(int *tabValue, int *tabOffsets, int &oldSize, int
newSize);
it means you can change the values of tabOffsets but not the pointer itself in order to make it behave correctly you should declare it as follows:
void changeSizeOfVector(int *tabValue, int **tabOffsets, int &oldSize, int
newSize);
This way you can change the pointer itself and assign a newly allocated array to it.