tags:

views:

81

answers:

2

Hi, My code compiles and run, but i've been told that it is quite problematic. I don't understand where do i go wrong.

Also, isn't it suppose to be wrong to declare "char _arrName[2];" and to do the assignment "_arrName[2]= '\0';" ? Isn't is a "out of boundaries" bug?

#include <iostream>
using namespace std;
class Base {
protected:
char* _name;
public:
virtual ~Base() { cout << "Base dtor of " << _name << endl; };
};
class D1: public Base {
char _arrName[2];
public:
D1() {
_name= _arrName;
_arrName[0]= 'D';
_arrName[1]= '1';
_arrName[2]= '\0';
}
virtual ~D1() { cout << "D1 dtor" << endl; }
};
int main () {
Base* arr[2];
arr[0]= new D1();
delete arr[0];
}
A: 

There is nothing wrong with your code. Perhaps it is because you haven't indented your code, which makes it 100x harder to read.

Though, some suggestions I would suggest you use std::string instead of plain C-style strings. It makes your job much easier.

Alexander Rafferty
Really, nothing?
Charles Bailey
+6  A: 

Yes, there is a definite error on this line.

_arrName[2]= '\0';

_arrName is an array of two char so you can only use the two values _arrName[0] and _arrName[1]. _arrName[2] is out of bounds.

Also there is an issue with this line.

virtual ~Base() { cout << "Base dtor of " << _name << endl; };

Because the derived class has pointed _name to point at an array member of the derived class, by the time ~Base() is called this array will have been destroyed and _name will no longer be pointing at a valid array.

There's the potential for error in the base class. _name is never initialized so it relies on derived classes initializing it. This is less than ideal design, although in practice it may or may not cause a real problem.

Charles Bailey
darven
@Mattityahu Shmuel: Just because something compiles and runs doesn't necessarily mean that the code is correct. Many forms of incorrect code (including both of these) cause _undefined behavior_. This means that the compiler doesn't have to diagnose the error but there are no constraints on what the program might do. Literally anything could happen. If you are lucky the code might crash and so give you some warning that there is an error.
Charles Bailey