0

I am in a introductory C++ course and my program is segfaulting in my copy function. when I use GDB it says it cant access the char * at location 0x0. the odd thing is that I have written this function many times before without any errors.

class question 
{
public:
question();
~question();
int set_question(char * question);
int copy_question(question & to_copy);
int clear_question();
int display(); 
char* retrieve_question();
char* retrieve_answer(); 
private:
char* your_question;
char* correct_answer;

};

///////////////////

int question::set_question(char * question)
{
your_question = new char [strlen(question)+1];
strcpy(your_question, question);

}

this is the error code in GDB

Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 1 (LWP 1)] 0x00013af8 in question::set_question (this=0x0, question=0x257a8 "do you like movies??") at question.cpp:51

51 your_question = new char [strlen(question)+1];

(gdb) p strlen(question)

$1 = 27

(gdb) p your_question

Cannot access memory at address 0x0

Gizmo
  • 1
  • 2

2 Answers2

0

I'm not professional at C++, but before you call member function set_question, are you initialized the class question? It seems that the question class is not initialized.

Kecise
  • 61
  • 6
0

You are calling the set_question method on a non-initialized object. You can see this from GDB output:

question::set_question (this=0x0, question=0x257a8 "do you like movies??")

'this' should not be 0x0

The problem is outside of this method. Basically, the newly allocated array cannot be assigned to 'your_question' member because the whole 'question' object is non existent.

You are probably not doing exactly the following, but this should illustrate the problem:

question *q = NULL;
q->set_question(...);
Patrik Beck
  • 2,455
  • 1
  • 19
  • 24