Monday, November 15, 2021

(C++) How to pass a variable type to a function

 E.g If you need to pass info like this:

void foo(type){
    // Other actions based on type
    cout << sizeof(type);

This cannot be done i.e. the type cannot be passed as a parameter since it is not a object and they do not exist at run time. They are only used by the compiler for type information building into the code. This can be instead fullfilled by templatinzing the function.

A template behaves in the following way:

template <typename T>

void foo(other_args) {

    // Other relevant data.

    T  somevar;

    cout << sizeof(somevar) << "    " <<sizeof(T);


Typenames can be also used to templatize classes in a similar fashion. 

Programming: Find location of Stack, Heap and current memory

 Simple code:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[]) {

    printf("location of code : %p\n", main);

    printf("location of heap : %p\n", malloc(100e6));

    int x = 3;

    printf("location of stack: %p\n", &x);

    return 0;


Note that %p prints the address of the pointer. 

Friday, June 18, 2021

Programming: Useful C or C++ Repositories


System Design

Consistent hashing implementation using MD5 & RB trees (C++) - GITHUB link

Message queue implementation (C++) - GITHUB

Hilbert space filling curve implementations (C and others) Link


MIT OCW C Course

Univ Wisconsin Madison OS Course

Saturday, May 8, 2021

(C++): Difference between angle bracket < > and double quotes “ ” while including header files in C?

From stackoverflow:
It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the spec (Section 6.10.2):


Fun: Another Optical Illusion

Optical illusion to trick your brain

Is this image made of concentric circles?

WiFi: What is phy restart? Why is it important in dense RF environments?

 Phy restart on radio drivers typically means if the hardware (radio) is able to sync to the preamble of a packet which has a stronger signal strength while it is already in the process of decoding a packet.

This is typically useful in noisy environments to achieve a "capture effect", where the stronger packet is finally decoded at the rx. radio. If the radio does not support PHY restart then typically such a reception would result in a collision on the rx-side at the radio.

Linux: How to move files between perforce changelists cls

 If you have a file opened as part of an existing changelist, how do we move the file to a different changelist.

Say for example you have created a CL234 and you want to move a file that is already present in your default Cl with the name //depot/test/main.c to your CL234.

The command to do this would be:
p4 reopen -c 234 //depot/test/main.c
The -c switch in the above command is used to specify the changelist#.

Friday, May 7, 2021

Linux: What does IRQ save do in Linux?

 ExcerptUse local_irq_save to disable interrupts on the local processor and remember their previous state. The flags can be passed to local_irq_restore to restore the previous interrupt state.

void local_irq_save(unsigned long flags);
void local_irq_restore(unsigned long flags);

The spinlock version will disable interrupts on all the cores*

Thursday, May 6, 2021

Wireless: Difference between WiMAX and LTE Physical and MAC layers

This is an old post based on excerpts I read from the web. Adding it back.

This post will cover the technological differences between these two technologies and contains a brief bullet point description as to why LTE took off and WiMAX did not:

Slot times: LTE uses much smaller slot times - 1ms as opposed to 4ms which gives much worse delay performance with multiple users and does not scale just as well.

Uplink modulation: LTE introduced SC-FDMA which dramatically improved uplink performance for cellular systems. This modulation technique combines the advantages of low peak to average ratio of traditional systems (such as GSM) and multipath resistance of newer modulation schemes (such as OFDM). SC-FDMA also provides savings for the mobile users (on their uplink).

Timing: WiMAX was the first to start off. Hence most of the experiments were performed on this and LTE could learn from their experience and MISTAKES. WiMAX was initially designed for fixed systems rather than mobile systems and they were not able to adapt well for usage with cellular providers.

Other non MAC/PHY differences:

WiMAX is based on IEEE standards (specifically, the 802.16 family), and then managed by the WiMAX Forum. LTE is defined by 3GPP.  

WiMAX was originally designed for fixed networks and has gradually evolved into a mobile network. But this has resulted in some changes not being  made correctly. LTE was designed as a mobile network from the first day. This particularly impacts the power at the receiver (handhelds). WiMAX handhelds are slated to consume more power as compared to LTE.

Wednesday, May 5, 2021

Linux: What is function cloning? Name.clone.XX seen in crash or symbols?

 Excerpt from an online post:

In the case of the gcc compiler, it make a copy of a function with some modifications for faster execution.For example, if the compiler discovers that a function is called many different times with the same couple of initial parameters, then it may clone the function to produce a version which takes fewer parameters, and then change all the invoking functions to call the cloned function named as fn-name.clone instead.

Also found this from another post:
"Another example is that a compiler may make several clones of a function and compile them tuned for different microarchitectures, and then arrange for the appropriate one to be used at runtime based on some sort of CPU test."

Monday, May 3, 2021

Linux: Why do we need an executable stack with nested functions in GCC


  • The stack needs to be writable because the trampoline code is written on the stack which needs to be executed (to jump to the nested function). 
A nested function has no linkage by itself. So the trampoline code actually ensures two things:
  1. The outer () functions stack frame is available in the nested function
  2. Jump and execute code from the nested function.
Some other notes:
  • Nested functions are not a part of ANSI C, however, they are part of Gnu C.
  • The only reason nested functions are possibly useful because they use common stack variables.

Friday, April 30, 2021

Math: Simple technique to implement moving averages in Java, C or C++

 The oneline solution is:

accumulator = (alpha * new_value) + (1.0 - alpha) * accumulator

Accummulator - holds the value being tracked
alpha - value between 0 and 1.

The more aggressive the alpha (closer to 1) the  faster the moving average adapts to the recent values. This is an exponential moving average.

Thursday, April 29, 2021

Linux: Poking the ethernet driver with the ethtool

 1. Get basic information about the interface

[mylinuxbox@mylinuxbox-linux ~]$ ethtool -i eth4
driver: e1000e
version: 2.1.4-k
firmware-version: 0.13-4
bus-info: 0000:00:19.0
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no

2. Dump all the hardware registers
[root@mylinuxbox-linux mylinuxbox]# ethtool -d eth4
MAC Registers
0x00000: CTRL (Device control register)  0x18100240
      Endian mode (buffers):             little
      Link reset:                        normal
      Set link up:                       1
      Invert Loss-Of-Signal:             no
      Receive flow control:              enabled
      Transmit flow control:             enabled
      VLAN mode:                         disabled
      Auto speed detect:                 disabled
      Speed select:                      1000Mb/s
      Force speed:                       no
      Force duplex:                      no
0x00008: STATUS (Device status register) 0x00080083
      Duplex:                            full
      Link up:                           link config
      TBI mode:                          disabled
      Link speed:                        1000Mb/s
      Bus type:                          PCI
      Bus speed:                         33MHz
      Bus width:                         32-bit
0x00100: RCTL (Receive control register) 0x04008002
      Receiver:                          enabled
      Store bad packets:                 disabled
      Unicast promiscuous:               disabled
      Multicast promiscuous:             disabled
      Long packet:                       disabled
      Descriptor minimum threshold size: 1/2
      Broadcast accept mode:             accept
      VLAN filter:                       disabled
      Canonical form indicator:          disabled
      Discard pause frames:              filtered
      Pass MAC control frames:           don't pass
      Receive buffer size:               2048
0x02808: RDLEN (Receive desc length)     0x00001000
0x02810: RDH   (Receive desc head)       0x00000051
0x02818: RDT   (Receive desc tail)       0x00000040
0x02820: RDTR  (Receive delay timer)     0x00000000
0x00400: TCTL (Transmit ctrl register)   0x3003F0FA
      Transmitter:                       enabled
      Pad short packets:                 enabled
      Software XOFF Transmission:        disabled
      Re-transmit on late collision:     disabled
0x03808: TDLEN (Transmit desc length)    0x00001000
0x03810: TDH   (Transmit desc head)      0x0000007A
0x03818: TDT   (Transmit desc tail)      0x0000007A
0x03820: TIDV  (Transmit delay timer)    0x00000008
PHY type:                                unknown

Tuesday, April 27, 2021

Latex: Customizing Footnotes for a neater look

There is a simple hack to do this:
\renewcommand{\thefootnote}{\arabic{footnote}}Arabic numerals, e.g., 1, 2, 3...
\renewcommand{\thefootnote}{\roman{footnote}}Roman numerals (lowercase), e.g., i, ii,... 
\renewcommand{\thefootnote}{\Roman{footnote}}Roman numerals (uppercase), e.g., I, II, ... 
\renewcommand{\thefootnote}{\alph{footnote}}Alphabetic (lowercase), e.g., a, b... 
\renewcommand{\thefootnote}{\Alph{footnote}}Alphabetic (uppercase), e.g., A, ... 
\renewcommand{\thefootnote}{\fnsymbol{footnote}}A sequence of nine symbols,

Changed mine to alphabets. Looks much neater now. 

Monday, April 26, 2021

Linux: Nagle's Algorithm and How to Disable it

 Nagle's algorithm is a TCP optimization in the kernel stack that waits to aggregate small chunks of bytes before sending packets on a TCP connection. This approach optimizes the amount of frame overhead spent in sending very small packets over the network. However, when the data is fairly sporadic, this could also lead to an increase in the average delay experienced.

Nagle's algorithm running on a host can be disabled by:
echo 1 > /proc/sys/net/ipv4/tcp_low_latency

Sunday, April 25, 2021

Linux: Kernel makefile system in brief

 There are multiple components in the kernel build system as shown in the table below:

Components in the Linux kernel build system

The Top makefile builds kernel image and modules. It does this by visiting directories recursively based on the kernel .config. The top Makefile textually includes an arch Makefile with the name arch/$(ARCH)/Makefile. The arch Makefile supplies architecture-specific information to the top Makefile. Each directory has a kbuild makefile which builds built-in or modular targets based on commands passed from above and info n the .config. Makefiles in the kernel are also referred to as kbuild files.

Further reading: A detailed discussion on these is available in the kernel documentation.