Computer Science, asked by owigocavine01, 9 months ago

what are the reasons why a program could not sometimes run when written in C++ program

Answers

Answered by vidhyakuludit92
1

Vatroslav Bodrozic

VATROSLAV BODROZIC

Vatroslav has 20+ years of programming experience. He enjoys complex, well-designed projects to challenge his passion for problem solving.

SHARE

There are many pitfalls that a C++ developer may encounter. This can make quality programming very hard and maintenance very expensive. Learning the language syntax and having good programming skills in similar languages, like C# and Java, just isn’t enough to utilize C++’s full potential. It requires years of experience and great discipline to avoid errors in C++. In this article, we are going to take a look at some of the common mistakes that are made by developers of all levels if they are not careful enough with C++ development.

Common Mistake #1: Using “new” and ”delete” Pairs Incorrectly

No matter how much we try, it is very difficult to free all dynamically allocated memory. Even if we can do that, it is often not safe from exceptions. Let us look at a simple example:

void SomeMethod()

{

ClassA *a = new ClassA;

SomeOtherMethod(); // it can throw an exception

delete a;

}

If an exception is thrown, the “a” object is never deleted. The following example shows a safer and shorter way to do that. It uses auto_ptr which is deprecated in C++11, but the old standard is still widely used. It can be replaced with C++11 unique_ptr or scoped_ptr from Boost if possible.

void SomeMethod()

{

std::auto_ptr<ClassA> a(new ClassA); // deprecated, please check the text

SomeOtherMethod(); // it can throw an exception

}

No matter what happens, after creating the “a” object it will be deleted as soon as the program execution exits from the scope.

However, this was just the simplest example of this C++ problem. There are many examples when deleting should be done at some other place, perhaps in an outer function or another thread. That is why the use of new/delete in pairs should be completely avoided and appropriate smart pointers should be used instead.

Similar questions