Friday, 30 August 2019

Vim goto definition

For navigation in large code bases. Mostly these have been tried with C/C++, but works similarly for other languages - Go, PHP, Elixir with some customization.
OS used - Ubuntu

Goto definition
Install ctags -> sudo apt-get install exuberant-ctags 
Activate ctags from project root -> ctags -R 
Open all source files from this project root in Vim
To goto function/variable definition under cursor -> Ctrl + ]  
To jump back ->  Ctrl + t  

Goto local variable/global variable declaration
If tag not found for some global variable/local variable/static/function
For definition and search(keyword under cursor) in same file(highlighter works with some good vim plugins) -> gd 
For global definitions -> gD 
To jump back -> Ctrl + o 

Goto header files
To go-to file ->   gf  
To jump back -> Ctrl + o 

This article will get updated more. The main aim is to keep it minimal.

Monday, 28 May 2018

ssh: Could not resolve hostname git: No address associated with hostname

I came across this error when I needed to clone a git repo. I tried few times but I couldn't get it working. There were few suggestions on the internet, but none resolved my issue.
So, lets get to the point, this issue may occur due to following reasons:

1. If you are using proxy to access git and it is not properly configured/proxy is not allowing you access git due to permission issues.
More here:

2. This happens due to a silly mistake. [I do make silly mistakes sometimes]
Are you actually using git clone for cloning? I used this -
ssh git@github.com:neovim/neovim.git
instead of
git clone git@github.com:neovim/neovim.git
-----
Hope this have resolved your issue :-)
Happy Coding.

Thursday, 8 June 2017

The First C Program - Hello World! : Behind the code

This code will print Hello World! as output.
#include <stdio.h>
int main()
{
  printf("Hello World!\n");
  return 0;
}
To understand more, I would recommend to go through following:

1. Preprocessor macros
# directive is for C preprocessor. #include simply looks for file stdio.h and includes the complete file in the current program. stdio.h is a header file which contains the declaration of variables, macros and functions of C standard library.

2. main() function
This is the function which acts as starting point for C program. Its return type is int, which is followed as per ISO C89/99 standard. The system considers a program to have run successfully if at the end, it returns 0. So, in my opinion, this might have been the reason to choose int as the return type of main.

3. Logic
Further, more functions and logic can be included inside main() to complete a desired task. In the above program, we are only printing one line and thats "Hello World!".

4. Return value
A function's return value can be used to return a value to be used further or to get status etc. Here, 0 is being returned to the system to indicate that the program ran successfully.

Monday, 29 August 2016

Installing Golang : The fast way

Steps only for Ubuntu. Other OS quick installation guide coming up soon!

So, this article is useful when you are in hurry and obviously, want to trust me :)


There are basically two ways to install golang - one is using the classical apt-get method and the other one is installing from source. he


First method

    $ sudo apt-get update
    $ sudo apt-get install golang

This will pretty much do the thing. Just two commands.
You can verify the installation just by checking this:
    $ go env GOROOT

This command will output the directory name where go is installed. Usually, it will show /usr/lib/go.

You can check go version:
    $ go version
    go version go1.5.1 linux/amd64

You are set to use golang. Please don't forget to configure $GOPATH and $GOBIN directories explained below. 

Note: This method will install go version which is included in os package. If you need to install particular version of go, read on.

Second Method

You can install go directly from source. Also, golang is a beautiful language. It is getting widely accepted and evolving periodically. So, you can install whatever version you want to.

Pre-requisites: Git should be preinstalled in your system to use this method as we will be cloning a git repo directly.

Following commands will create a directory named which will be go installation directory. You can run them anywhere. To make it easy for you, do it in home directory ;-)
    $ git clone https://go.googlesource.com/go
    $ cd go
    $ git checkout go1.7
    $ cd src
    $ ./all.bash

If everything is fine, you  should see the below output:
ALL TEST PASSED

Most important step, set your GOPATH and GOBIN path variables

Now, to utilize go development at its fullest, go programs are generally written in a directory which will all the go related packages, dependencies.

In short, you just create a directory and consider it as your workspace for go programs. A directory, anywhere. Later this directory will hold three sub directories - src, pkg, bin. 
src - will contain all the source code.
pkg - will contain all the packages which your source code will use.
bin - will contain the binary files.

But the go compiler should know where this directory is. So, just follow this
    $ mkdir gocode
    $ cd gocode
    $ mkdir src pkg bin

Set the paths
    $ export GOPATH=$HOME/gocode
    $ export GOBIN=$GOPATH/bin

Provided your gocode directory is in home directory. Now to avoid exporting the path each time you login, you need to put these commands in bashrc or similar file.

    $ vim ~/.bashrc
    * Append the two export commands in this file and save.

Sunday, 12 July 2015

Expandable Arrays in C : behind the code

Arrays. They are beautiful.
In C, we always try to work through restrictions arrays have i.e the size of the array must be statically defined. We always want a dynamic array whose size can be decided at run-time. There are ways which we use widely for e.g by using pointers and then dynamically allocating memory to it using malloc or calloc. But depending on the situation, we might require more efficient and organizable ways. I will explain the concept with a series of examples as in how simple arrays evolved to the tricky expandable ones.

The classic way is to use pointers
This snippet will allocate a memory block of size = array_size(integer array).
Though this is not what I wanted to explain because this way is too clumsy. Imagine if you need 10 dynamic arrays in your program, you have to write these four lines each time and you have to keep track of all the 10 sizes.

A better way is to use structures:
We can simply create a structure containing two elements: array_size and a pointer variable. We can allocate memory to this pointer variable dynamically. This will save us from the headache of keeping track of different array sizes.
For a better understanding, visualize this:
- In this example, we have taken first and second as Array variable, so we don't need to free them. In the end, we only need to free memory of first.arr and second.arr
Its neat and evolved from the first method and this is widely used in software industries. Though I can assure you, expandable arrays are more interesting.
So, moving to our discussion:

What are expandable arrays?
Expandable arrays or stretchable arrays are a tricky way to create dynamic arrays with a pre-defined data structure and its quite very similar to above method.
See the following, and note the area which is marked as expanded memory:

This seems more complex, right? But its not!
  • We created a structure which contains last element as a 1 element array.
  • As the last element is an array with size 1 and not a pointer, so we can't allocate memory to this. The trick is to create a pointer variable to structure Array and allocate memory to it of whatever size we want.
  • Typically, we should have allocated memory of size struct Array to its pointer, but here we allocate size of structure plus (array_size - 1). We subtract 1 because we already have memory for 1 variable.
  • As you can see, now we have some extra memory at the tail of the structure, to which we can traverse using arr[].
  • We can organise and wrap the functionality into more structured way, e.g, create a separate init function etc.
When you think clearly, this method will seem illegal. But that's the fun of it. :)

Why expandable arrays?
Generally, data has two parts: metadata + actual data.
Metadata is information about data viz. name, creation date, ownership, size etc. We can use expandable arrays beautifully in those scenarios in which we have to transfer data along with some metadata and the size of actual data is not certain.
For e.g, consider a system level software which is used to download data into your mobile phone. The size of file might be known(assume 1 GB), but the transfer rate depends on speed of your internet. At one moment, if the speed is 1 Mbps, the array_size will be 1 Mb for that second. For the next second, if the speed changes to 2 Mbps, we can transfer more data, so array_size will be 2 Mb. In this case, we can use a data structure as above, transferring variable sized data at each second, and utilizing memory with less chances of leaks and memory corruption.
Try writing a program to do this, you will learn a lot. :-)
--------------------------------
Let me know if you find any errors or something is not clear.

Monday, 28 October 2013

Stack Size : behind the code

How to know the stack size of a process in Linux?
#Interview Question

The stack word is very popular when it comes to C programming. It often intrigues us that how much is the stack size of a process and how to know it.
The answer to this question can not be given without considering the "platform independent" thing. Well, we all are familiar with the word "platform independent". It is only word which comes to our mind when we don't know the answer. :P
So, the stack size depends on the platform, the architecture - microprocessor is of how many bits - 16, 32, 64? But I will explain the answer with respect to Linux operating system.

Method 1
The simplest method which I found is through
cat /proc/-pid-/limits
  • cat command is used to access a file.
  • proc is a directory which contains information about all the running processes.
  • -pid- is the process id of the process. We can know the process id of any process using ps -ef command. See man page of ps for more.
E.g:
I wrote a simple C program. And I put an infinite loop in that program(using while( )) so that it will be running. Then I used ps -ef to find out the -pid- of the process. I found it to be 3274. Then I did the following:
gene@user-laptop:~$ cat /proc/3274/limits
Limit                 Soft Limit     Hard Limit         Units  
Max cpu time          unlimited      unlimited          seconds
Max file size         unlimited      unlimited          bytes  
Max data size         unlimited      unlimited          bytes  
Max stack size        8388608        unlimited          bytes
Max core file size    0              unlimited          bytes  
Max resident set      unlimited      unlimited          bytes  
Max processes         32084          32084              processes
Max open files        1024           4096               files  
Max locked memory     65536          65536              bytes  
Max address space     unlimited      unlimited          bytes  
Max file locks        unlimited      unlimited          locks  
Max pending signals   32084          32084              signals
Max msgqueue size     819200         819200             bytes  
Max nice priority     0              0                 
Max realtime priority 0              0                 
Max realtime timeout  unlimited      unlimited          us 
Check out the line which is marked- Max stack size.
It is 8388608 bytes = 8 MB.

Method 2
There is also a different method to find out the stack size programmatically :
We can find out the stack size using getrlimit( ) system call.
Read about it :
gene@user-laptop:~ man getrlimit
Below is a program to find out the stack size of a process:
After running this program, we will get this output (Linux):
gene@user-laptop:~ gcc -ostacksize stacksize.c
gene@user-laptop:~ ./stacksize
Lower limit = 8388608
Upper limit = 4294967296
These results are in bytes. So, the stack size is 8388608 bytes = 8 MB for a 32 bit processor. The upper limit is the maximum limit upto which size of the stack can be incremented. It is 4294967296 bytes = 4 GB(size of virtual memory space assigned to a process). Though it is 4GB, incrementing it to this limit may overwrite certain other important data.
There is also a system call prlimit which is used to find out the stack size of any arbitrary process. I am leaving that for you to try. Tell me if you face any problem.
I have kept this explanation very compact because it can be found in man page of getrlimit. Still if anyone want more explanation here, just comment below.
-----
Feel free to give suggestions. :)

Monday, 21 October 2013

error: invalid application of ‘sizeof’ to incomplete type ‘struct ’

list.c:47:39: error: invalid application of ‘sizeof’ to incomplete type ‘struct Litsnode’

So, I was trying to run a program based on linked list and this is what I got.
This is a very silly problem. I am mentioning it here just to help those who got frustrated like me :-\


Let me show you the line where this error occurred :

46  struct Listnode * newnode;
47  newnode = (struct Listnode *) malloc(sizeof(struct Litsnode));

Now, View it properly. Check the name(spelling) of the structure mentioned to sizeof : "struct Litsnode". Though the defined name of the structure was : "struct Listnode"

That's it. 
This happens all the time that we may type something wrong. The important thing is to identify it. :-)

Feel free to give any suggestions :)