I'm trying to debug these code, and the first one gives me a segmentation fault.
I feel like there might be...
Types of Errors to Find/Correct/Match
Off by one error in an array
Initialize a different object than the one you are using
Forget “Big Three” with dynamic member variable
Access memory that hasn’t been allocated
There are two different bugs
bug1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef STATE_H_
#define STATE_H_
class state {
private:
char *name;
int pop;
public:
void set_name(constchar *);
void display_pop();
void set_pop(int);
state();
virtual ~state();
};
#endif /* STATE_H_ */
#include "state.h"
#include <iostream>
usingnamespace std;
int main() {
state s[50];
int which_state;
cout << "Which state do you want? (1-50)";
cin >> which_state;
s[which_state-1].set_pop(300000);
s[which_state-1].set_name("oregon");
s[which_state-1].display_pop();
return 0;
}
#include "nation.h"
#include "state.h"
#include <iostream>
usingnamespace std;
int main() {
int which_state;
state s[50];
cout << "Which state do you want to set the pop? (1-50):";
cin >> which_state;
s[which_state].set_pop(300000);
s[which_state].display_pop();
return 0;
}
When I enter any numbers between 70 through 75, it gives me the population and the state. But when I enter anything outside of 75 and 70, it gives me a segmentation.
The second seems okay, I think? But the state number doesn't get printed
In bug1, name is a pointer, but what does it point to? You initialize it to NULL in the constructor. It looks like it should point to dynamic memory, but that means you'll need to allocate the memory in set_name()
- and delete an old name if it exists
- and delete the name in the destructor
- and create a copy constructor that copies the name
- and create an assignment operator that copies the name
Sigh.... This is why it's a really good idea to use string instead. It does all of this for you.
It is very important for a program to test that the input looks appropriate. Here the program asks: "Which state do you want to set the pop? (1-50):"
... while you, as user, write "70", which to my knowledge is not within (1-50).