Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
langcpp

class Base {
public:
	virtual void func(void) {
		cout << "Base" << endl;
	}
};

class Derived : public Base {
public:
	int i;
	Derived() { i = 0; }

	void func(void) {
		cout << "Derived " << ++i << endl;
	}
};

void walk(class Base *bar, int count) {
	for (int i = 0; i < count; i++) {
		bar[i].func();
	}
}

int main(void) {
	Base dis[3];
	Derived dat[3];

	walk(dis, 3);
	walk(dat, 3); // crashes
}

...

Code Block
bgColor#ccccff
langcpp

void walk(class Base *bar [], int count) {
	for (int i = 0; i < count; i++) {
		(bar[i])->func();
	}
}

int main(void) {
	Base* dis[3] = {new Base, new Base, new Base};
	Base* dat[3] = {new Derived, new Derived, new Derived};

	walk(dis, 3);
	walk(dat, 3);

  for (int i = 0; i < 3; i++) {
    delete dis[i];
    delete dat[i];
  }
}

...

Code Block
bgColor#ccccff
langcpp

void walk(vector<Base*>bar) {
	for_each (bar.begin(), bar.end(), mem_fun(&Base::func));
}

int main(void) {
	vector<Base*> dis(3);
        for (int i=0; i<3; i++) dis[i] = new Base;

	vector<Base*> dat(3);
        for (int i=0; i<3; i++) dat[i] = new Derived;

	walk(dis);
	walk(dat);

  for (int i = 0; i < 3; i++) {
    delete dis[i];
    delete dat[i];
  }
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ARR39-CPP

high

likely

high

P9

L2

Automated Detection

Tool

Version

Checker

Description

 PRQA QA-C++

 
Include Page
PRQA QA-C++_v
PRQA QA-C++_v
3072,3073 

Bibliography

[Sutter 04] Item 100: Don't treat arrays polymorphically.

...