Need help with debugging process

closed account (10X21hU5)
The following code is compiled and debugged on linux.

p.s. headers are omitted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class P
{
public:
   P() {}
   P( const string &s ) : str( s ) {}
   void assign( const string & );
   void print() const;
   P &append( const P & );

private:
   string str;
};

void P::assign( const string &s )
{
   str = s;
}

void P::print() const
{
   cout << str << endl;
}

P &P::append( const P &p )
{
   str += p.str;
   return *this;
}

int main()
{
   P *p1 = (P*)malloc(sizeof(P));
   P *p2 = (P*)malloc(sizeof(P));

   p1->assign("Good");
   p2->assign(" morning");

   (*p1).append(*p2).append(P(" everybody"));

   p1->print();
}


I tried debugging the above code in gdb; when I tried printing the
information in p1, I got the following error:
$10 = {str = <error reading variable: Cannot access memory at address 0xfffffff4>}

Can someone tell me what's happening here? Many thanks in advance~
Last edited on
You shouldn't be creating new instances of class P by calling malloc.
Doing so, bypasses the constructor for class P.
This then does not initialize the member string [str] in P.

You should rather be instantiation new instances via the new method as:
1
2
   P *p1 = new P();
   P *p2 = new P();


To utilize malloc to mannualy allocate memory for class P can be done when overiding the new operator. This however, is only useful if you want to allocate memory for an instance of P from a memory pool. When overiding the new operator in such cases, we still have class P's constructor firing.

However, in your case below, if you examine string constructor you may try the floowing hack - this is hwoever not safe and is only listed for purpose of understanding mechanics behind new and malloc abit.

1
2
3
4
5
6
7
8
   void * pv1 = malloc(sizeof(P));
   void * pv2 = malloc(sizeof(P));

   memset(pv1, 0, sizeof(P));
   memset(pv2, 0, sizeof(P));

   P *p1 = (P*)pv1;
   P *p2 = (P*)pv2;
Topic archived. No new replies allowed.