This is the part of the code where I'm facing the problem:
#include<iostream>
using namespace std;
struct ID{
int value;
ID *nxtElement;
};
struct SqLand{
ID *id;
SqLand *next;
};
int main(){
for(int p, i = 0; i < 3; i++){
SqLand *nptr = new SqLand;
cin >> p;
ID *buff = new ID;
buff = nptr->id;
for(int j = 0; j < p; j++){
cin >> buff->value;
//cout << "Garbage";
buff = buff->nxtElement;
}
buff = NULL;
//cout << "WILL";
delete nptr;
delete buff;
}
return 0;
}
The problem is that on running this program and inserting the value of p more than 1, the program exits after 2 more inputs.
For example, starting like this:
2
1
3
This is where the program exits
If both the cout statements are un-commented here are the outputs:
2
1
Garbage3
GarbageWILL
And another:
3
1
Garbage2
Garbage
All the programs exit after their respective last lines. What is the error in my program? It's a part of another program so that don't expect this snippet to make any sense. I only want to know where it goes wrong.
What i can understand from your code this ... (with fix)
struct ID {
ID(int val = -1, ID* _nxtElement = NULL) :
value(val), nxtElement(_nxtElement) {
}
int value;
ID *nxtElement;
};
struct SqLand {
SqLand(ID* _id = NULL, SqLand* _next = NULL) :
id(_id), next(_next) {
}
ID *id;
SqLand *next;
};
const int size = 3;
int main() {
SqLand* head = new SqLand;
SqLand* tmp = head;
for (int p, i = 0; i < size; i++) {
cin >> p;
tmp->id = new ID;
ID* tmpID = tmp->id;
for (int j = 0; j < p; j++) {
cin >> tmpID->value;
// avoid unnecessary allocate
if (j < p - 1) {
tmpID->nxtElement = new ID;
tmpID = tmpID->nxtElement;
}
}
// avoid unnecessary allocate
if(i < size - 1) {
tmp->next = new SqLand;
tmp = tmp->next;
}
}
return 0;
}
in your code you miss allocate for nptr->id and you miss the most important the head of list (SqLand *nptr = new SqLand;).
Related
struct Student
{
char* name;
int balls;
};
void inputdata(Student **s, int *n)
{
int nn;
printf("%s\n", "Input amount of students");
scanf("%i", &nn);
Student* a = new Student[nn];
for (int i = 0; i < nn; ++i)
{
a[i].name = new char[4096];
scanf("%4095s", a[i].name);
scanf("%i", &a[i].balls);
}
*n = nn;
*s = a;
}
void print(Student *s, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%s %i\n", s[i].name, s[i].balls);
}
}
void fixdata(Student *s, int *n)
{
int nn = *n;
for (int i = 0; i < nn; ++i)
{
if (s[i].balls > 100)
s[i].balls = 100;
else if (s[i].balls < 20)
{
for(int j = i; j < nn; ++j)
s[j] = s[j+1];
nn-=1;
}
}
*n = nn;
}
int main(int argc, char const *argv[])
{
Student* s;
int n;
inputdata(&s, &n);
print(s, n);
fixdata(s, &n);
print(s, n);
return 0;
}
I am trying to delete items where balls is less than 20. If so, I am supposed to shift items to the right, but at the same time remove items that are less than 20. I try, but it drastically shifts left 2 of the same records and is not doing the job properly.
UPDATE: Ok, I cleaned up the code a bit, now n decreases, but the problem when it stays at 1 record, that is supposed to be deleted too. I wonder why it does not get removed. Thankfully most of the trouble is fixed. Still, what is the problem deleting one item left when it is less than 20?
The function has a bug because after moving elements of a sub-array to the left in the next iteration of the for loop you will deal with another element instead of the required. Also the function should return the number of actual elements after removing some elements.
Also the function can produce memory leaks then one element of the array is assigned to other element of the array.
The function can look the following way
int fixdata( Student *s, int n )
{
int i = 0;
for ( int j = 0; j < n; ++j )
{
if ( not ( s[j].balls < 20 ) )
{
if ( i != j )
{
delete [] s[i].name;
s[i] = s[j];
s[j].name = nullptr;
}
if ( s[i].balls > 100 ) s[i].balls = 100;
++i;
}
}
return i;
}
And in main you can write
int m = fixdata(s, n);
print(s, m);
Also you should delete the allocated memory when the array is not needed any more.
for ( int i = 0; i < n; i++ )
{
delete [] s[i].name;
}
delete [] s;
In fixdata(), when "removing" an item, you are leaking that item's name, but more importantly your inner loop goes out of bounds of the array if the "last" item is removed.
Try this instead:
void fixdata(Student *s, int *n)
{
int nn = *n;
for (int i = 0; i < nn; ++i)
{
if (s[i].balls > 100)
{
s[i].balls = 100;
}
else if (s[i].balls < 20)
{
for(int j = i + 1; j < nn; ++j)
{
delete[] s[j-1].name;
s[j-1] = s[j];
s[j] = Student{};
}
--nn;
}
}
*n = nn;
}
That being said, your code is more C than C++. The C++ approach would be to use things like std::cin, std::string, and std::vector instead, eg:
#include <iostream>
#include <vector>
#include <string>
struct Student
{
std::string name;
int balls;
};
std::istream& operator>>(std::istream &in, Student &stud)
{
in >> s.name >> s.balls;
return in;
}
std::ostream& operator<<(std::ostream &out, const Student &stud)
{
out << stud.name << " " << stud.balls;
return out;
}
void inputdata(std:vector<Student> &s)
{
int nn;
std::cout << "Input amount of students\n";
std::cin >> nn;
std::vector<Student> a(nn);
for (auto &stud : s) {
std::cin >> stud;
}
s = std:move(a);
}
void print(const std::vector<Student> &s)
{
for (const auto &stud : s) {
std::cout << stud << "\n";
}
}
void fixdata(std::vector<Student> &s)
{
for (size_t i = 0; i < s.size();)
{
auto &stud = s[i];
if (stud.balls < 20) {
s.erase(s.begin()+i);
}
else {
if (stud.balls > 100) {
stud.balls = 100;
}
++i;
}
}
/* alternatively:
s.erase(
std::remove_if(s.begin(), s.end(),
[](const auto &stud){ return (stud.balls < 20); }
),
s.end()
);
std::for_each(s.begin(), s.end(),
[](auto &stud){ stud.balls = std::min(stud.balls, 100); }
);
*/
}
int main()
{
std::vector<Student> s;
inputdata(s);
print(s);
fixdata(s);
print(s);
return 0;
}
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];
}
};
I am trying to implement a radix sort using queue structure but it's giving me an error. can anyone help me with this please. thanks
using the c++ library queue, the program works perfectly fine so there is something wrong with my queue structure or the way I initialize the array of 10 queues or maybe the way I use pointers.btw I am a beginner. thanks
#include<iostream>
#include<cstdlib>
#include<ctime>
//#include<queue>
#include<cmath>
using namespace std;
struct node{
int value;
node* next;
};
struct que{
node* frontt;
node* rear;
};
void enqueue(que* &queu,int value)
{
node* newNode = new node;
newNode->value = value;
newNode->next = nullptr;
if(queu->rear !=nullptr)
{
queu->rear->next = newNode;
queu->rear = newNode;
} else{
queu->frontt = queu->rear = newNode;
}
}
int dequeue(que* &queu)
{
node* temp = new node;
int returnValue;
if(queu->frontt){
temp = queu->frontt;
returnValue = temp->value;
queu->frontt = queu->frontt->next;
delete temp;
if(!queu->frontt){
queu->rear = nullptr;
}
}
return returnValue;
}
void radixSort(int q[], int n);
int main() {
const int MAX = 9;
int radix[MAX] = {2, 543, 23, 123, 900, 4, 3, 2, 223};
for (int j = 0; j < MAX; j++)
cout << radix[j] << " ";
cout << endl << endl;
radixSort(radix, MAX);
for (int j = 0; j < MAX; j++)
cout << radix[j] << " ";
cout << endl << endl;
return 0;
}
void radixSort(int arr[], int n) {
que* arrayOfQues[10];
//queue<int> arrayOfQues[10]; //one array per possible digit
int maxDigits = 3; //holds amount of digits in largest number
int currentDigit = 0; //starting base for decimal digit
while (currentDigit < maxDigits) {
for(int i = 0; i < n; i++){ //loop through whole array
int divisor = pow(10, currentDigit);
int num = arr[i]; //set to current value of array position
int digitValue = static_cast<int>((num / divisor) % 10); //get the decimal digit at current digit
enqueue(arrayOfQues[digitValue],num);
//arrayOfQues[digitValue].push(num); //put digits in corresponding arrayOfQues
}
int i = 0;
for(int k = 0; k < 10; k++){ //loop through all arrayOfQues
while(arrayOfQues[k]->frontt != nullptr){
//while(!arrayOfQues[k].empty()){ //push all elements in bin[k] until empty to a
/*int temp = arrayOfQues[k].front();
arr[i] = temp;
arrayOfQues[k].pop();
i++;*/
arr[i] = dequeue(arrayOfQues[k]);
}
}
currentDigit++;
}
}
I'm trying to make an arraylist class where I make a moving Average function in my arraylist class while outputting the moving average of my arraylist class.
I've tried various research and examples online and I've officially hit a wall. Can someone please help me fix my problem. I really need to get this fixed as soon as possible. Code was provided by my professor.
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#include<iostream>
using namespace std;
class arrayList {
int size;
int capacity;
double * p;
void resize() {
capacity *= 2;
double * temp = new double[capacity];
for (int i = 0; i < size; i++) {
temp[i] = p[i];
}
delete[] p;
p = temp;
}
}
public:
arrayList(): size(0), capacity(1) {
p = new double[capacity];
}
arrayList(int cap): size(0), capacity(cap) {
p = new double[capacity];
}
//copy constructor
arrayList(const arrayList & copy) {
size = copy.size;
capacity = copy.capacity;
p = new double[capacity];
for (int i = 0; i < size; ++i)
p[i] = copy.p[i];
}
//move constructor
arrayList(arrayList && move) {
size = move.size;
capacity = move.capacity;
p = move.p;
move.size = 0;
move.capacity = 0;
move.p = nullptr;
}
//copy assignment operator
arrayList & operator = (const arrayList & copyA) {
if (this != & copyA) {
size = copyA.size;
capacity = copyA.capacity;
p = new double[capacity];
for (int i = 0; i < copyA.size; ++i)
p[i] = copyA.p[i];
delete[] p;
}
return *this;
}
// move assignment operator
arrayList & operator = (arrayList moveA) {
if (this != & moveA) {
size = moveA.size;
capacity = moveA.capacity;
delete[] p;
p = moveA.p;
moveA.p = nullptr;
}
return *this;
}
//destructor
~arrayList() {
delete[] p;
}
void insert(int index, int value) {
if (index >= capacity) {
cout << "OUT OF BOUNDS!";
}
if (index < size && index >= 0) {
for (int i = size; i > index; --i) {
p[i] = p[i - 1];
}
p[index] = value;
size++;
} else {
p[index] = value;
size++;
}
}
void append(int val) {
if (size == capacity)
resize();
p[size] = val;
size++;
}
void movingAvg(const arrayList & val, int kernel) {
for (int i = 0; i < val.size; ++i) {
kernel = val.p[i];
val.p[i] = kernel[val.size - 1 - i];
kernel[size - 1 - i] = kernel;
cout << "average of the array is: " << val.p;
}
friend ostream & operator << (ostream & os, arrayList & val) {
for (int i = 0; i < val.size; ++i)
os << val.p[i] << " ";
os << endl << endl;
return os;
}
};
// main.cpp
int main() {
arrayList a;
a.append(45);
cout << a;
a.append(14);
cout << a;
a.insert(2, 76);
cout << a;
//CRASHES AT THIS POINT!
a.insert(3, 45);
cout << a;
a.insert(5, 23);
cout << a;
return 0;
}
OUTPUT:
45
45 14
45 14 76 0
You are deleting p more than once in your resize function. That's likely the source of your crash.
Instead of this:
void resize(){
capacity *= 2; //THIS IS WHAT'S CRASHING THE CODE
double *temp = new double[capacity];
for(int i = 0; i < size; i++){
temp[i] = p[i];
delete []p;
p = temp;
temp = nullptr;
}
}
Implement this:
void resize() {
capacity *= 2;
double *temp = new double[capacity];
for (int i = 0; i < size; i++) {
temp[i] = p[i];
}
delete [] p;
p = temp;
}
And if you want to be more efficient with the copy loop:
void resize() {
capacity *= 2;
double *temp = new double[capacity];
memcpy(temp, p, sizeof(double)*size);
delete [] p;
p = temp;
}
I'm writing an easy Game Of Life simulator. Everything works smoothly except at the very end, when the result is printed by cout I get a break error. I don't understand why and I would like to ask for your help.
variables
#include <iostream>
using namespace std;
struct cell
{
bool isAlive;
int posX;
int posY;
int numberOfAliveNeighbours;
char group;
};
int cellNumber;
cell *cellTable = new cell[cellNumber];
int numberOfTunrs;
main:
int main()
{
int x;
int y;
int cellCounter = 0;
cin >> x >> y;
cellNumber = x*y;
cin >> numberOfTunrs;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
char cellAliveChar;
cin >> cellAliveChar;
if (cellAliveChar == '#')
{
cellTable[cellCounter].isAlive = true;
}
else if (cellAliveChar == '.')
{
cellTable[cellCounter].isAlive = false;
}
cellTable[cellCounter].numberOfAliveNeighbours = 0;
cellTable[cellCounter].group = '#';
cellTable[cellCounter].posX = j;
cellTable[cellCounter].posY = i;
cellCounter++;
}
}
doTurns(x, y);
int result;
result = countGroups();
**cout << result << endl;**
//here is breakpoint
cin >> x;
}
countGroups (idk if it's relevant):
int countGroups()
{
int max = 0;
int current;
int i = 0;
char checkingGroup = 'A';
do
{
current = 0;
for (int j = 0; j < cellNumber; j++)
{
if (cellTable[j].group == checkingGroup + i)
{
current++;
}
}
i++;
if (current > max)
{
max = current;
}
} while (current != 0);
return max;
}
the breakpoint screenshot:
Click to view the screenshot
The problem is cellTable declaration:
int cellNumber;
cell *cellTable = new cell[cellNumber];
Global variables are implicitly initialized with 0 so cellNumber will point to array of 0 size and any attempt to access cellTable items leads to undefined behavior.
It would be better to make all variables local and pass them to functions explicitly. Instead of manually allocating array you should use std::vector, or at least allocate after assigning an appropriate number to cellNumber (after getting x and y values).