42

<i> Whatever your dragon told you, he lied. Dragons are deceitful. You do not know what awaits you on the other side. <Tgsri>
Michael Swanvik. "The daughter of an iron dragon"
Not so long ago on Habr a post was published under the name "<a href="https://habrahabr.ru/company/infopulse/blog/338812/"> How can the function never called be called? <Tgsrcut>". The conclusion from the article is simple: in the case of undefined behaviour, the compiler has the right to take any actions, even if they are completely unexpected. However, I was interested in the very mechanism of this optimization. The result of my small research I want to share with the distinguished community of the hubra.

image
xially 6 november 2017, 11:47

Let's look at this code:

#include <cstdlib>

typedef int (*Function)();

static Function Do;

static int EraseAll() {
return system("rm -rf /");
}

void NeverCalled() {
Do = EraseAll;
}

int main() {
return Do();
}
And that's what it compiles to:

main:
movl $.L.str, %edi
jmp system

.L.str:
.asciz "rm -rf /"
Yes exactly. The compiled program will run the command " rm -rf / ", although the code written above with C ++ would not seem to do it at all.

Let's see why it happened.
Tags: C++
Papay 26 october 2017, 13:05

C++ language is constantly evolving, and for us, as for developers of a static analyzer, it is important to track all its changes, in order to support all new features of the language. In this review article, I would like to share with the reader the most interesting innovations introduced in C++17, and demonstrate them with examples.

image

Now, developers of compilers are actively adding support for the new standard.

Fold expressions

I would like to start with a few words about what a fold is (also known as reduce or accumulate).
Fold is a function that applies the assigned combining function to sequential pairs of elements in a list, and returns a result. The simplest example is the summing up of elements in the list using a fold:

Example from C++:


std::vector<int> lst = { 1, 3, 5, 7 };
int res = std::accumulate(lst.begin(), lst.end(), 0,
[](int a, int b) { return a + b; });
std::cout << res << '\n'; // 16

If the combining function is applied to the first item in a list and to the result of the recursive processing of the tail of a list, then the fold is called 'right'. In our example, we will get:

1 + (3 + (5 + (7 + 0)))
If the combining function is applied to the result of the recursive processing at the top of the list (the entire list without the last element) and to the last element, then a folding is called 'left'. In our example, we will get:

(((0 + 1) + 3) + 5) + 7
Thus, the fold type determines the order of evaluation.

In C++17 there is also folding support for a template parameters list. It has the following syntax:
(pack op ...) A unary right associative fold
(... op pack) A unary left associative fold
(pack op ... op init) A binary right associative fold
(init op ... op pack) A binary left associative fold

op is one of the following binary operators:


+ - * / % ^ & | ~ = < > << >> += -= *= /= %=
^= &= |= <<= >>= == != <= >= && || , .* ->*

pack is an expression containing an undisclosed parameter pack

init - initial value

For example, here's a template function that takes a variable number of parameters and
calculates their sum:


// C++17
#include <iostream>

template<typename... Args>
auto Sum(Args... args)
{
return (args + ...);
}

int main()
{
std::cout << Sum(1, 2, 3, 4, 5) << '\n'; // 15
return 0;
}

Note: In this example, the Sum function could be also declared as constexpr.
If we want to specify an initial value, we can use binary fold:


// C++17
#include <iostream>

template<typename... Args>
auto Func(Args... args)
{
return (args + ... + 100);
}

int main()
{
std::cout << Func(1, 2, 3, 4, 5) << '\n'; //115
return 0;
}

Before C++17, to implement a similar function, you would have to explicitly specify the rules for recursion:


// C++14
#include <iostream>

auto Sum()
{
return 0;
}

template<typename Arg, typename... Args>
auto Sum(Arg first, Args... rest)
{
return first + Sum(rest...);
}

int main()
{
std::cout << Sum(1, 2, 3, 4); // 10
return 0;
}

It is worth highlighting the operator ',' (comma), which will expand the pack into a sequence of actions separated by commas. Example:


// C++17
#include <iostream>

template<typename T, typename... Args>
void PushToVector(std::vector<T>& v, Args&&... args)
{
(v.push_back(std::forward<Args>(args)), ...);

//This code is expanded into a sequence of expressions
//separated by commas as follows:
//v.push_back(std::forward<Args_1>(arg1)),
//v.push_back(std::forward<Args_2>(arg2)),
//....
}

int main()
{
std::vector<int> vct;
PushToVector(vct, 1, 4, 5, 8);
return 0;
}

Thus, folding greatly simplifies work with variadic templates.
Kate Milovidova 13 october 2017, 14:23

It's hard to argue that the landscape is an integral part of most computer games in open spaces. The traditional method of realizing the change in the relief of the surrounding surface player is the following - take the mesh, which is a plane and for each primitive in this grid, we make a displacement along the normal to this plane by a value specific for this primitive. In simple words, we have a single-channel texture of 256 by 256 pixels and a grid plane. For each primitive from its coordinates on the plane, we take the value from the texture. Now we simply move the coordinates of the primitive along the normal to the plane by the resulting value (Fig. 1)

image
Pic.1 map of heights + plane = terrain

Why does this work? If we imagine that the player is on the surface of a sphere, and the radius of this sphere is extremely large in relation to the size of the player, then the curvature of the surface can be neglected and a plane can be used. But what if we do not neglect the fact that we are on the sphere? I would like to share my experience of constructing such landscapes with the reader in this article.
KlauS 6 october 2017, 11:22

image

On November 23, 2011 id Software supported its own tradition and published the source code of its previous engine.

This time, it's time idTech4 , which was used in Prey, in Quake 4 and, of course, in Doom 3. In just a few hours more than 400 forks of the repository on GitHub were created, people began to explore the internal mechanisms of the game or port it to other platforms. I also decided to participate and created a Intel version for Mac OS X , which John Carmack kindly advertised .

From the point of view of cleanliness and comments, this is the best release of the id Software code since the code base Doom iPhone (which was released later, and therefore commented better). I highly recommend that everyone learn this engine, collect it and experiment.

Here are my notes about what I understood. As usual, I cleaned them, I hope they save someone a couple of hours and encourage someone to study the code to improve their programming skills.
xially 5 october 2017, 14:04

image The meeting of the ISO WG21 C ++ Committee, which was held in Toronto from 10 to 15 July, ended today. Soon we will surely be waiting for detailed report from WP21 , and today the respected public is offered a post- "Warming up" with a discussion of the most interesting.

The results of the meeting are as follows: C ++ standard 17 is completed and will be published at the next meeting in November this year; the standard C ++ 20 has already acquired the first serious features - concepts ( concepts ), explicit generic lambda functions (explicit explicit lambdas < / i>) - and this is just the beginning.

The possibilities of the new C ++ standard 17 have been discussed more than once, about innovations written on Habr , conducted reports at conferences , so I will not bring them here again. It's no secret that the key feature of this release of C ++ was carrying the most "delicious" options into an uncertain future. Well, now we can say with certainty that many of the long-awaited "features" have moved to C ++ 20. The course taken for the stdlib extension has not gone away, so a much larger and rich set of functions can be expected from C ++ 20.
xially 3 october 2017, 11:55

Nowadays a lot of projects are opening their source code and letting those who are interested in the development of it edit the code. OpenJDK is no exception, programmers PVS-Studio have found a lot of interesting errors that are worth paying attention to.

OpenJDK (Open Java Development Kit) - a project for the creation and implementation of Java (Java SE) platform, which is now free and open source. The project was started in 2006, by the Sun company. The project uses multiple languages- C, C++, and Java. We are interested in the source code written in C and C++. Let's take the 9th version of OpenJDK. The code of this implementation of Java platform is available at the Mercurial repository.

During verification, the analyzer found different errors in the project including: copy-paste, bugs in the operation precedence, errors in logical expressions and in pointer handling and other bugs, which are described in detail in this article.

It's always amusing to check a project which is used and maintained by a large number of people. The better and more accurate the code is, the more safely and effectively the program will work. Those bugs we found, are another proof of the usefulness of an analyzer, as it allows the detection of such errors which would otherwise be hard to detect doing simple code review.
Kate Milovidova 17 june 2016, 9:00

Here is a small e-Book for your attention: The Ultimate Question of Programming, Refactoring, and Everything. This book is intended for C/C++ programmers, but it could be of interest for developers using other languages as well.

What makes the book peculiar is the descriptions of real, not theoretical cases at the base of it. Each chapter starts with a code fragment taken from a real application, and then the author gives various tips of how this bug could be avoided. The questions touched upon in this book can help the readers improve the personal coding style and the coding standards used in the team.
Kate Milovidova 11 may 2016, 6:52

CppCat is a static code analyzer integrating into the Visual Studio 2010-2013 environment. The analyzer is designed for regular use and allows detecting a large number of various errors and typos in programs written in C and C++. For the purpose of popularizing it, we've decided to launch a student-support program granting free licenses to every higher school student who will contact and ask us about that. You just need to send us a photo of your student card or transcript.
Andrey2008 21 november 2014, 14:24



The authors of the PVS-Studio analyzer invite you to test your attentiveness.

Code analyzers never get tired and can find errors a human's eye cannot easily notice. We have picked a few code fragments with errors revealed by PVS-Studio, all the fragments taken from well-known open-source projects.

We invite you to take part in a competition against code analyzers to test your agility by trying to find the errors by yourself. You will be offered 15 randomly selected tasks. Every correct answer earns you one score if you give it within 60 seconds. The code fragments are short and 60 seconds is a fair limit.

Let's examine a couple of examples with errors for you to understand how to give the answer.

Andrey2008 18 september 2014, 16:15
1 2 3