Understanding unique_ptr with Example in C++11

The smart pointers are a really good mechanism to manage dynamically allocated resources. In this article, we will see unique_ptr with example in C++11. But we don’t discuss standard smart pointers from a library. Rather, we implement our own smart pointer equivalent to it. This will give us an idea of inside working of smart pointers. Brief Prior to C++11, the standard provided std::auto_ptr. Which had some limitations. But from C++11, standard provided many smart pointers classes....

September 15, 2019 · 8 min · 1571 words · Vishal Chovatiya

C++ Type Casting With Example for C Developers

The typecasting is the feature which makes C++ more type-safe, robust & may convince you to use it over C. But this is also a more underrated topic when you are a newbie or moving from C background. Hence, I come up with an article on it. Here, we will not only see the C++ type casting with example but we will also cover Why do we need typecasting? & C++ type casting cheat codes for C developers to remember & employ it easily....

September 12, 2019 · 10 min · 1948 words · Vishal Chovatiya

Complications of Using the Virtual Base Class

In the previous article about How Does Virtual Base Class Works Internally? we have seen address resolution of virtual base class & why it’s needed. But I have not discussed Complications of Using the Virtual Base Class. Which we will see in this article. This is going to be a bit complex & clumsy then learning the internal working of the virtual base class. But if you are not tired, then read forward....

September 12, 2019 · 8 min · 1500 words · Vishal Chovatiya

Part 3: All About Virtual Keyword in C++: How Does Virtual Destructor Works?

Finally, we are in the 3rd & last part of this series. We have already discussed how virtual function & virtual class/inheritance works internally in previous parts. We left one topic i.e. “How Does Virtual Destructor Works?” which we will see now. As usual, before learning anything new I usually start with “Why Do We Need It in the First Place?” Why Do We Need a Virtual Destructor? We will understand this with our earlier example(slightly twisted): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class protocol_t { private: uint8_t *_type; // storage ....

September 12, 2019 · 6 min · 1194 words · Vishal Chovatiya

When to Use const vs constexpr in C++

While introducing myself to Modern C++ & its new features introduced in C++11 & C++14, I have completely neglected this keyword constexpr. Initially, I was confused about when to use const vs constexpr in C++ & how this constexpr works & differ with const. So, I have studied this from different sources & here is the consolidation of it: Primitive constexpr Variables 1 2 3 int varA = 3; const int varB = 5; constexpr int varC = 7; All of the above variable having a value which is known at compile time....

September 12, 2019 · 5 min · 935 words · Vishal Chovatiya

2 Wrong Way to Learn Copy Assignment Operator in C++ With Example

While I was introducing myself to C++, I was confused about the syntax of the copy assignment operator in C++ & some of its use-cases. I have learned those lessons the hard way. And so I have decided to write this article, where we see 2 wrong way to learn copy assignment operator in C++ with example. And we also see why we need it & why its syntax like that only....

September 11, 2019 · 9 min · 1705 words · Vishal Chovatiya

All About Copy Constructor in C++ With Example

Do not carry away with the title “All about copy constructor in C++ with example”. In this article, I am not going to describe what copy constructor in C++ is. There is plenty of material available for that over the internet. Rather we will discuss why, where & how it used, how compiler synthesizes it for you and in what scenarios it called or not synthesized. Why: Copy Constructor The simple answer is to copy the data within the same data types, but if you want more concrete idea then see below image:...

September 11, 2019 · 5 min · 862 words · Vishal Chovatiya

Inside the C++ Object Model

This article is the collection of concept I have acquired while introducing myself to C++ by googling here & there. This material is also not in order. I have just collected the answer to my quick question. And write it down here. But one thing I can assure you is that once you go through this article. You can connect many broken thought of understanding on what runs “Inside the C++ object model”....

September 11, 2019 · 5 min · 928 words · Vishal Chovatiya

Memory Layout of C++ Object in Different Scenarios

In this article, we will see the memory layout of different C++ Object. And how different storage & access specifiers affect this memory footprint. I am not going to discuss compiler augmented code, name mangling & working of any C++ mechanism related to memory as it is compiler & architecture-dependent. To keep this further simple, I have considered the standard stack growth direction i.e. downwards. And with the same, data members are represented inverted in memory(thanks to Thomas Vermeilh for pointing that out), that too I have ignored for simplicity....

September 11, 2019 · 8 min · 1676 words · Vishal Chovatiya

Part 1: All About Virtual Keyword in C++: How Does Virtual Function Works Internally?

“All About Virtual Keyword in C++” is a series of articles(total of three, PART 1, PART 2, PART 3) describe working of the virtual keyword in different scenarios. This article mostly focuses on “How Does Virtual Function Works Internally?”. In other words, How dynamic dispatch done in C++! Although I am not a compiler writer, but this is what I have learned so far from various sources, courses, books & disassembly of C++ program....

September 11, 2019 · 9 min · 1746 words · Vishal Chovatiya

Part 2: All About Virtual Keyword in C++: How Does Virtual Base Class Works Internally?

In PART 1 of “All About Virtual Keyword in C++” series, we have discussed “How Does Virtual Function Works Internally?”. So, in this article, I will discuss “How Does Virtual Base Class Works Internally?”. I am iterating the same thing which I have mentioned in the earlier article as well that implementation of a virtual mechanism is purely compiler dependent. So, there is no C++ standard is defined for such dynamic dispatch....

September 11, 2019 · 6 min · 1249 words · Vishal Chovatiya

How Does Virtual Memory Work?

Have you ever wondered , How game of size 8 GB is running on a computer has 4 GB of RAM only? or You can play multiple movies simultaneously combined size more than RAM size? If you are a software developer, you may come across a word like multi-tasking or multiprocessing which is key concept behind this. In other words, it creates virtual memory which is a memory management technique. Here we will see how it works...

October 15, 2016 · 5 min · 894 words · Vishal Chovatiya

How Do malloc & free Work in C!

As we know, the process can allocate & deallocate memory using malloc & free in C language. But do you ever consider what happens behind the scene ? or How do malloc & free work? Let see Allocating Memory on the Heap A process can allocate memory by increasing the size of the heap. Heap is a variable-size segment of contiguous virtual memory that begins just after the uninitialized data segment of a process and grows & shrinks as memory allocated and freed....

October 8, 2016 · 5 min · 876 words · Vishal Chovatiya

Dynamic Linking Example

Following example covers API like dladdr, dlclose, dlerror, dlopen, dlsym and flags like RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL, `RTLD_LOCAL, `RTLD_NODELETE`, `RTLD_NOLOAD`, RTLD_NEXT, RTLD_DEFAULT, etc. At First Sight, This Might Look Lengthy & Alien, But If You Spend 5 Min, You Might Get What You Looking For. I Struggle With Finding Dynamic Linking Example On Net When I Came Across Dynamic Linking Related Development. So I Wrote One Helping Post. flags.c We will create binary flags out of flags....

September 30, 2016 · 5 min · 981 words · Vishal Chovatiya

GNU Build System: Automake, Autoconf, Libtool

Brief GNU Build System: Automake, Autoconf, Libtool are a suite of programming tools used to make source code packages portable to many Unix-like systems. Why We Need Autotools: Autoconf: automatically generates configure script by scans of existing tree to find its dependencies, that are supposed to work on all kinds of platforms. configure generates a config.h file (from a template) which programs can include to work around portability issues. For example, if HAVE_LIBPTHREAD is not defined, use forks instead....

September 30, 2016 · 5 min · 933 words · Vishal Chovatiya

How Program Gets Run: Linux

I know it’s long, but please bear with me & have patience. How do we launch our programs? Do you know how programs get runs behind the screen when you double-click on it or you type ./a.out on shell As you know, the standard way to launch an application from a shell is to start terminal emulator application & just write the name of the program & pass or not arguments to our program, for example: 1 2 3 4 5 6 7 8 [vishal@machine Desktop]$ ls --version ls (GNU coreutils) 8....

September 25, 2016 · 12 min · 2354 words · Vishal Chovatiya

How to hack C/C++ application using RTLD_NEXT with an easy example

While I was working as a core C library developer with my previous employer. I came across this RTLD_NEXT flag in dynamic linking which has the amazing capability and can be easily exploited or used for unethical purpose(Here I intend to educate the developer to don’t be victims). In this article, I will show you a simple way to hack C/C++ application using RTLD_NEXT with an easy example. Brief Let say you have a C/C++ application/tool which is highly proprietary and driving most of the business to your company....

September 25, 2016 · 5 min · 1046 words · Vishal Chovatiya

A Bit About mmap

Points to Catch mmap()is system call used to maps files or devices into memory Linux provides the `mremap( ) system call for expanding or shrinking the size of a given mapping. POSIX defines the `mprotect( ) interface to allow programs to change the permissions of existing regions of memory. Synchronizing a File with a Mapping: A system call msync( ) flushes back to disk any changes made to a file mapped via mmap( ), synchronizing the mapped file with the mapping *Advantage of mmap() over open(), read()& write()` mmap is great if you have multiple processes accessing data in a read-only fashion from the same file which saves many system calls or context switching overheads Useful for inter-process communication....

September 10, 2016 · 3 min · 465 words · Vishal Chovatiya

A Bit About vfork

What is vfork ? It’s a special case of a clone. It is used to create new processes without copying the page tables of the parent process. calling thread is suspended until the child call execve or _exit. Points To Remember vfork()is an obsolete optimization. Before good memory management, fork()made a full copy of the parent’s memory, so it was pretty expensive. since in many cases a fork()was followed by `exec(), which discards the current memory map and creates a new one, it was a needless expense....

September 10, 2016 · 2 min · 256 words · Vishal Chovatiya

Binary semaphore example between threads in C

Semaphore is a synchronization mechanism. In more words, semaphores are a technique for coordinating or synchronizing activities in which multiple processes compete for the same resources. There are 2 types of semaphores: Binary semaphores & Counting semaphores. But our focus would be on binary semaphore only. That too binary semaphore example between threads in C language specifically. If you are in search of semaphore between processes then see this. As its name suggest binary semaphore can have a value either 0 or 1....

September 10, 2016 · 3 min · 450 words · Vishal Chovatiya

Clone system call example

This is a quick article on Clone system call example without talking shit. So let’s see some pointers for the same : clone() creates a new process, in a manner similar to fork. It is actually a library function layered on top of the underlying clone()system call. Unlike fork , these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers....

September 10, 2016 · 2 min · 419 words · Vishal Chovatiya

Create Process Using fork()

Points To Catch When we fork in any process it simply creates a copy of the same process which we call child process 1 2 Parent Child return PID 0 Fork returns 0 in the child process & PID of the child process in the parent process, which you can see in above example. returns -1 on failer. Create copy of process including memory variables & stored value in it with its own address space Example 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <stdio....

September 10, 2016 · 2 min · 323 words · Vishal Chovatiya

CRT: C Run Time Before Starting main()

There are a lot of functions called before & after the main execution. As an application developer you need not worry about this stuff, but yes! if you are a core developer who works in Linux kernel, Binutils, compiler or embedded system-related development, then you must know these things. Here in “CRT: C run time before starting main”, we will see some pointers related to it. What Is crt? crt stands for C runtime....

September 10, 2016 · 3 min · 568 words · Vishal Chovatiya

Dealing with Multiple file descriptor : poll() system call

Why use poll()? Suppose you have to deal with multiple clients connected at the same time. A natural question, then, is: how can you read from multiple file descriptors (sockets) at once? Do you need to make some really annoyingly multi-threaded code to handle each client that’s connected? Do you have to go into some stupid loop constantly checking each socket to see if data’s available? You can resolve this issue efficiently by polling file descriptor(Sockets here)....

September 10, 2016 · 2 min · 266 words · Vishal Chovatiya

Error Handling : setjmp & longjmp

Points To Catch As for the control flow: setjmp returns twice, and longjmp never returns. When you call setjmp for the first time, to store the environment, it returns zero, And then when you call longjmp, the control flow passes to return from setjmp with the value provided in the argument. Use cases are generally cited as “error handling”, and “don’t use these functions”. Note: setjmp needn’t actually be functions; it may well be a macro....

September 10, 2016 · 2 min · 263 words · Vishal Chovatiya

Execute Threads Parallelly at Given Time: pthread_barrier_t

Why we need pthread_barrier_t? When multiple threads are working together, it might be required that the threads wait for each other at a certain event or point in the program before proceeding ahead. Let us say we have four threads, each of which is going to initialize a global variable. The 4 variables, in turn, might be used by all the four threads. Thus it would be feasible that all the threads wait for each other to finish the initialization of the variables before proceeding....

September 10, 2016 · 3 min · 478 words · Vishal Chovatiya

Semaphore between processes example in C

Semaphore is a synchronization mechanism. In more words, semaphores are a technique for coordinating or synchronizing activities in which multiple processes compete for the same resources. There are 2 types of semaphores: Binary semaphores & Counting semaphores. Binary Semaphores: Only two states 0 & 1, i.e., locked/unlocked or available/unavailable, Mutex implementation. Counting Semaphores: Semaphores which allow arbitrary resource count called counting semaphores. Here, we will see the POSIX style semaphore. POSIX semaphore calls are much simpler than the System V semaphore calls....

September 10, 2016 · 3 min · 455 words · Vishal Chovatiya

Shared Memory IPC

Brief As the name suggests, shared memory is a memory that may be shared by multiple programs with an intent to provide communication among them or avoid redundant copies. Points To Catch shmget() Creates a shared memory segment, The key argument could be semaphore ID shmat(): Shared segment can be attached to a process address space using this API It can be detached using shmdt(), A shared segment can be attached multiple times by the same process The original owner of a shared memory segment can assign ownership to another user with `shmctl() List out shared memory areas by ipcs -m Get more info on the particular shared memory area ipcs -m -i [shmid] Remove shared memory ipcrm shm [shmid] Server....

September 10, 2016 · 2 min · 410 words · Vishal Chovatiya

Signal Handling

Points To Catch Signals = software interrupts. The command kill -l on the bash would give us the following. 1 2 3 4 5 6 7 8 9 10 11 12 13 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX Signals are also delivered to a process with the help of kill command....

September 10, 2016 · 2 min · 380 words · Vishal Chovatiya

Socket Programming

Points To Catch On a single system, Two processes can communicate through Pipes Message queues Shared memory To communicate between two processes over a network, you need Socket Socket = Endpoint of communication between two systems on a network OR Combination of IP & Port Number Server Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 #include <sys/socket....

September 10, 2016 · 3 min · 620 words · Vishal Chovatiya

Thread Conditional Wait with Mutex : pthread_cond_t

Brief Condition variables provide yet another way for threads to synchronize. While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data. Without condition variables, the programmer would need to have threads continually polling (possibly in a critical section), to check if the condition is met. This can be very resource consuming since the thread would be continuously busy in this activity....

September 10, 2016 · 3 min · 520 words · Vishal Chovatiya

Understand ELF file format

ELF is the file format used for object files (.os), binaries, shared libraries and core dumps in Linux. ELF has the same layout for all architectures, however endianness and word size can differ; relocation types, symbol types and the like may have platform-specific values, and of course, the contained code is arch-specific. An ELF file provides 2 views on the data it contains: A linking view and an execution view....

September 10, 2016 · 9 min · 1916 words · Vishal Chovatiya

Unix Domain Socket

Brief A Unix domain socket or IPC socket is a data communications endpoint for exchanging data between processes executing on the same host operating system. The API for Unix domain sockets is similar to that of an Internet socket, but rather than using an underlying network protocol, all communication occurs entirely within the operating system kernel. Unix domain sockets use the file system as their address namespace. Processes reference Unix domain sockets as file system inodes, so two processes can communicate by opening the same socket....

September 10, 2016 · 3 min · 633 words · Vishal Chovatiya