Skip to main content

Posts

Showing posts with the label advancedCpp

How to quickly investigate memory leak in your application

Every C/C++ software developer meet problem of memory leak (allocating memory over time which is not freed). If you would like to know how to investigate memory leak problem in your application, this article is for you. For memory leak investigation I recommend to use valgrind tool. Especially with it's Massif tool. Let's see the example how we could use that tool for memory leak investigation. Below snippet of code has lots of points where memory leak can occur. 1 #include <stdio.h> 2 3 void allocmem1 () 4 { 5 char * memleak 2 = malloc ( 100 * sizeof ( char )) ; 6 } 7 8 void allocmem2 () 9 { 10 char * memleak 2 = malloc ( 10 * sizeof ( char )) ; 11 allocmem1 () ; 12 } 13 14 void allocmem3 () 15 { 16 char * memleak 2 = malloc ( 5 * sizeof ( char )) ; 17 allocmem2 () ; 18 } 19 20 int main ( int argc , const char ** argv ) 21 { 22 char * memleak 1 = malloc ( 5 * sizeof ( char )) ; 23 ...

Advanced C++ - Stack unwinding

Stack unwinding is normally a concept of removing function entries from call stack (also known as Execution stack, Control stack, Function stack or Run-time stack). Call Stack is a stack data structure that stores active functions' addresses and helps in supporting function call/return mechanism. Every time when a function is called, an entry is made into Call stack which contains the return address of the calling function where the control needs to return after the execution of called function. This entry is called by various names like stack frame , activation frame or activation record. With respect to exception handling , stack Unwinding is a process of linearly searching function call stack to reach exception handler. When an exception occurs, if it is not handled in current function where it is thrown, the function Call Stack is unwound until the control reaches try block and then passes to catch block at the end of try block to handle exception. Also, in this proc...

Advanced C++ - Exceptions

Exception handling is programming feature helpful for programmers to handle run time error conditions. Run time error conditions can be like division by zero, unable to allocate memory due to scarcity, trying to open a file which doesn’t exist etc. There are two types of exceptions. One is Standard exceptions provided by C++ Standard library and other type is User defined exceptions. Now, to handle any exception, we should understand 3 main block of exception statement which are as follows: throw block - in this block, we throw an exception. The operand of the throw statement decides the type of exception occurred. Once this line is executed, program jumps to catch block to handle the exception occurred. catch block - is the block where we handle exception. This is also called as exception handler and this block is written immediately after the try block as shown in example. This can be written similar to a normal function with at leas...

Advanced C++ - virtual functions

Today I am going to explain some basic but very important C++ feature - polymorphism and inheritance which is based on virtual functions in C++. Virtual functions can be declared by preceding the function with virtual keyword. The importance of Virtual functions can be understood, when we design classes using inheritance. Virtual functions are special functions which are called using late binding concept. Late binding or dynamic binding means that the binding happens during run time using vtable (virtual table) to select the correct virtual method to be called as the code runs. Let us look at an example for getting more clarity on how Virtual functions work in reality: Output of that example is: Point 1 shows how virtual function is declared and defined. Point 2 shows the inheritance concept i.e class Derived is inherited from class Base using public access specifier. In point 3, virtual function of class Base is redefined in class Derived which leads to f...

Advanced C++ - Mutable Class Field

Today I would like to present C++ class' feature called mutable class field . Mutable class field is class' field modifier which allows to change its value even if object of the class is declared as const . Take a look at the example: Output of this example is: In point I of that example we are defining object of TestClass . Note that this object is const . As you can see in point Ia this class has three different member fields ( constInt, mutableConstInt, nonConstInt ). Those variables are public for this example, but do not worry about encapsulation here. It is just omitted for simplify this example. As you can see one of this member fields is marked as mutable class file using mutable keyword ( mutableConstInt ). Such variable can be modified even if object of class TestClass is const . It will be explained in next points of this example. In point II we are printing default values of testObject object initialized in initialization list of TestClass' default c...

Advanced C++ - Effective C++ - cheatsheet

I would like to share with you my summary of the "Effective C++" book by Scott Meyers . It is very interesting book for everyone who would like to improve C++ developments skills to be every effective. I highly recommend it. Quick summary of that book, which I prepared you can download after by clicking on below image. Summary of Effective C++ book by Damian Ziobro

C++ Multithreading - Basic thread creation

C++11 standard introduces integrated sublibrary for multithreading . It has been moved from Boost library. However because multithreading is very important topic in software development I decided to make multithreading tutorial as separate section of this blog. I will not explain here theory about multithreading, but I will try to explain usage of multithreading based on thread library from C++11 standard. If theory explanation will be required for some aspects I will try to put links to separate articles explaining them. Introduction theory about multithreading you can find on Wikipedia article here This article will present basic threads creation and usage in C++. Code of example you can find here: Output of the example is (it can be little other - depends how thread will be invoked by OS): In point I we are creating new thread where print() function will be invoked. This thread will work in parallel to the main function (main application is second thread called main...

C++11 - Lambda functions

C++11 standard introduces new type of functions for C++ programming - lambda functions. Lambda function is a anonymous (unnamed) function which you can write directly inline in the code. Lambda function allows do some operations visible like a function without declaring it as a function (saving space and time). C++ lambda function has following syntax: [capture](arguments){body} capture - value which should be captured outside of body class arguments - list of arguments of function (the same syntax as for normal C++ functions) body - body of function - statements which should be exectued when function is invoked For better understanding take a look fo below example: Output of this example is: In point I we are initializing vector using C++11 initializer_list Point II is key point of our example. It demonstrate using lambda function (3rd argument of for_each function) together with with for_each algorithm of STL library in order to calculate sum of vector element...

lvalue - definition

Today I found very interesting definition of lvalue  in C++. According to this site: An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the  &  operator. An rvalue is an expression that is not an lvalue.  Examples are: // lvalues: // int i = 42; i = 43; // ok, i is an lvalue int* p = &i; // ok, i is an lvalue int& foo(); foo() = 42; // ok, foo() is an lvalue int* p1 = &foo(); // ok, foo() is an lvalue // rvalues: // int foobar(); int j = 0; j = foobar(); // ok, foobar() is an rvalue int* p2 = &foobar(); // error, cannot take the address of an rvalue j = 42; // ok, 42 is an rvalue

Advanced C++ - Template classes

Template class concept is similar to template functions . It allows creating generic type classes, which means that we can have many different classes which differ only in terms of types using one class code only. See example below for better explanation: Output of this example is: Point I depicts definition of template class. As you can see it is very similar to definition of template function. We are defining myType as type which will be replaced with real type during usage of template class. Then we are defining class normally with usage of mapped temporary type. Points II and III shows how to use template class for different class. We are defining two instances of our template class - for int and double types. Compiler will implicitely generate bodies of two clases based on those types and template definition. As for template functions, we are selecting real type using angle brackets. Above example you can find on our github repository here: https://github.com/xmeme...

Advanced C++ - Template Functions

Template function are special types of C++ function which can be used with different types (generic types). Thanks to that we can create one body of function which can be used for many different types. When we are creating template function compiler does not define any function for use at that time. Generation of funciton basing on templates are done during compilation process basing of differnt usage of template class. For better understanding take a look on following example: Output of this example is: In point I, we are defining template function which should return sum of two parameters. Without templates we need to define such function separately for each type which we should use it with (ex. separate function for int type, separate for double , separate for any other type). Thanks to template we can generate body of that function only once (as in point I) and use it to any type which is able to use body of that function. In our example we can use this template for an...

Advanced C++ - Conversion constructor and operator

When we are defining class we sometimes would like to allow easily convert that class from and to previously defined-type objects (ex. int ). We can do that using conversion constructor and conversion operator: conversion constructor - it is constructor which has one parameter - type which constructor should allow to convert from. It allows to convert previously defined object of type as in constructor paramter into object of class where constructor belongs to conversion operator - it is overloaded operator type() - where type is type of object which we can convert this class object into Let's see below example for better understanding: Output of this example is: In that example in our class TestClass we are defining two conversion constructors. conversion constructor for type int (point I) conversion constructor for type string (point II) Next in main function we are invoking that constructors converting int and string types to our class TestClass type (p...

Advanced C++ - Compiler generated functions

When we define some class in our C++ code, compiler is generating some important functions for our class (unless we define it explicitly). Those functions (sometimes called Compiled Generated Functions ) are:  default constructor   destructor   copy constructor   copy assignment operator  During compilation, compiler knows our code and classes usage, so when we are using one of above functions implicitly, it generate that function implicitly for us in the class body. For better explenation, let's see the example below: In point (I) we are defining class TestClass . This class seems to be empty. However we are implicitly using following function in main class:  point III - we are implicitly using defualt constructor in order to create instance of TestClass - default constructor of TestClass is implicitly generated by compiler   point IV - we are using copy constructor of TestClass in order to copy instance to...

Advanced C++ - Function object

Function object is object which has function-call operator ( operator() ) defined or overloaded. Thanks to that objects have behaviour of function which means that you can call such object by using paranthenses and passing arguments. Let's see and example: The output of this example is: In point (II) we are defining function object according to class defined in point (I). In point (III) we are using our function object like a normal function.  You may be considering what is advantage of usage function object instead of normal function. Here are few advantages of function object:   1. Function object can be used as normal function but can has also additional abilities related to being object ex. the same function, represente by different function object, can has different states at the same time.   2. Function object has own types. What is more different function objects can has different states even if they signature is the same. This is very useful in STL lib...

Advanced C++ - Anonymous namespaces

Anonymous namespace is kind of namespace with no specified name. Such kind of namespace is visible only within file where it is defined within. I allows define variables and functions which could be visible as global, but within one file only. Thanks to that such files are not global within whole program. It also allow avoids making global static variable. Let's see an example of defining and usage of anonymous namespace. Consider following main.cpp file: In the above example we have anonymous namespace containing one int typed variable. This variable can be used as global variable withing this main.cpp file but will not be visible inside any other files. That is simple example of usage anonymous variables. If you would like to compile it and play with it (changing or adding some parts of code to check what happends than) you can download it from here:  https://github.com/xmementoit/CppAdventureExamples/tree/master/advancedCpp/anonymousNamespace