coming up with social content site

all these days busy in building up new social content site. using python django as my framework.

learnt many things abt software project management. Things I have learnt are

1) you will never finish enhancements . once u come up with idea and do coding daily...new ideas come up and its upto you to decide which features to ship to satisfy your clients.

2) things you think easy may take more time..and some other things you  think hard may get finished
in lesser time.

3) modules that are not doable by you can be outsourced but not to cost of wasting money and time.

4) for any kind of product , people hate the word 'slow'. along with functional requirements make sure performance requirements are fulfilled.

5) technical things I have learnt are .
a) python , django framework
b) hitting db always doesnt scale. so used memcached for caching
c) divide project into subproblems..abstract the core module so that other developers can work on that and enhance the project later.
d) write wrapper for modules which are used frequently rather than duplicating the code.

and finally
e) do not re-invent the wheel again just to show that you can code complex things...I came across open source project memcached for using in memory cache to save DB hits. it saved lot of time for my project and many famous social portels like facebook use it. so its okay for me to use memcached as my in-memory cacheing

finally looking ahead for front end developer who can add colors to my website and look it attractive like heroine ileana :) lolz just kidding .

will blog again once I complete my social content site :) . 

find least common ancestor in Binary search tree


Q)least common ancestor for binary search tree

recursive way of doing is here. In BST, all values lesser than root will be on left subtree, values greater than root will be on right subtree.

node *ancestor=NULL

node * LCA(node *root,node *n1, node*n2)
{

if(n1 == NULL && n2 == NULL)
  return root ;

if(n1 == NULL)
 return n2;

if(n2==NULL)
  return  n1 ;

return findLCA(root,n1,n2) ;
}

node *findLCA(node *root,node *n1,node *n2)
{
ancestor=root;

if(n1->data < root->data && n2->data < root->data)
 return LCA(root->left,n1,n2)
else if(n1->data > root->data && n2->data > root->data )
return LCA(root->right,n1,n2)
else
return ancestor;

}

Binary tree Questions



1) how to merge two Binary search trees

A) convert the each binary tree to Single LL using inorder traversal
merge two LL and copy to array.

construct binary tree with mid element as root. if you want to balance tree then we can use AVL tree rotations.

node *prev=NULL;
node *head=NULL:

converttoLL(Treenode *root,node **head)
{
if(root !=NULL)
{
converttoLL(root->left,&head)

if( *head==NULL )
*head=prev=(node *)root;
else{
prev->next=root;
prev=root;
}

convertoLL(root->right,&head)

}//..end if(root !=NULL)
}

constructroot(Treenode *&root,int mid)
{
Treenode *temp=new Treenode();
temp->data=mid;
temp->left=null;
temp->right=null;
root=temp;

}

constructtree(Treenode *&root, int element)
{
Treenode *curr=root;

while(curr!=NULL)
{
 if(curr->data <= element )
curr=curr->left;
else
curr=curr->right;
}

Treenode *temp=new Treenode();
temp->data=mid;
temp->left=null;
temp->right=null;

curr=temp;

}

int main(){

// main method
node *head1=NULL ;
node *head2=NULL;

ConverttoLL(Tree1,&head1);
ConverttoLL(Tree2,&head2);

node *n2=head2;
while(n2!=NULL)
{
node *save=n2->next ;
merge( &head1 , n2 ) ;
n2=save;
}
code for merge is in
http://techie-builder.blogspot.in/2012/06/linked-lists-questions.html

node *n1=head1;
int a[100];
int i=0;

while(n1!=NULL)
{
a[i]=n1->data ;
i++;
n1=n1->next ;
}

constructroot(a[i/2]);

for(int j=0;j < i ; j++ )
{
if(j!=i/2) // already we constructed root
constructtree(a[j]);
}


}

Merge Sort iterative way

recursive way is very easy to write for merge sort. generally interviewers now a days asking for iterative way..here is mergesort in iterative way. this prints elements in ascending manner.

NOTE: some of greater , lesser operators could be missing due to bloging issues .


#include
#include
#include
using namespace std  ;

void merge(int [],int,int,int);
int main()
{
int a[100];

int j=0,size=0;
for(int i=10;i > =0; i--){
++size;
a[j++]=i;
}

int mergelen=2,start=0;
int i=0;
int mid=0;
int lastmerge=0;
while(mergelen < size)
{

for(i=0;i < size; i=i+mergelen)
{
if((i+mergelen) < size){
mid=i+mergelen/2 ;
merge(a,i,i+mergelen-1,mid);
}
else{
mid=(i+(size))/2;
merge(a,i,size-1,mid+1);
}
lastmerge=i;
}
mergelen=mergelen * 2 ;
}
merge(a,0,size-1,lastmerge);
cout<<"final"<
//print elements here.
getchar();return 0;
}


void merge(int a[],int start,int mergelen,int size)
{
cout<<"\n pass "<
int temp[100];
//cout<<"\n pivot is "<
int i=start,j=size,k=0;
while(i < size && j <= mergelen)
{
//cout<<"\n exchanging "<
if(a[i]>a[j]){
temp[k]=a[j];
k++;j++;
}
else{
temp[k]=a[i];
k++;i++;
}
}
while(i < size )
temp[k++]=a[i++];

while(j < = mergelen)
temp[k++]=a[j++];


for(int index=0;index < k ; index=index+1)
a[start++]=temp[index];

}




binary semaphore vs mutex

binary semaphore take 0 and 1 values. so we may think only 1 thread can access the resource.
but in semaphore there is nothing like ownership of resource and also other thread can
increment the semaphore . In mutex only the thread which acquired the lock can release the lock and the
thread is owner of the lock. developers uses mutex for  mutually exclusive lock instead of binary semaphore.

data structures - interview questions

I got few requests to post questions on linked lists,trees,graphs , sorting algorithms etc. i will be blogging when i have time for this.

first linked lists questions are here

http://techie-builder.blogspot.in/2012/06/linked-lists-questions.html

sortings:

http://techie-builder.blogspot.in/2012/07/merge-sort-iterative-way.html

Arrays:
https://techie-builder.blogspot.in/2016/06/generate-subsets-of-array-using-python.html

Linked Lists - Questions


Q1) how do you reverse a single linked list.
a) there are num of ways to do this. 1 way is just keep on iterating through linked list and add those nodes at head of new linked list

pseudo code is here

node* reverse(node *elem)
{
if (elem == NULL) return NULL;
if (elem->next == NULL) return elem ;
node *n1 = reverse(elem->next);
if(n1 != NULL)
    n1->next = elem;
return n1;
}


alternative way is reversing pointers in place



Node* reverse(Node* root) {
  Node* new_root = 0;
  while (root) {
    Node* next = root->next;
    root->next = new_root;
    new_root = root;
    root = next;
  }
  return new_root;
}



Q2) deleting a node in single Linked list

A)
Node deleteNode(Node head, int d) {
Node n = head;
 if (n.data == d) {
 return head.next; /* moved head */
 }
 while (n.next != null) {
 if (n.next.data == d) {
 n.next = n.next.next;
 return head; //just return head
 }
 n = n.next;
 } //end while
 }

Q3) get last n nodes in single linked list of unknown length

A) In single list list, we can only go fwd direction. so how do we get last n nodes, if we don't know the length of linked list .

approach 1: when we keep traversing the list, store the nodes in stack. when we reach end of linked list, pop up the stack 'n' times. but we are going to waste the space as we are storing all linked list nodes in stack. space complexity is O(n) . so what can we do about saving the space in stack?. we can store the nodes in Queue now when we traverse the linked list , when ever the Queue length crosses the 'n' we remove the elements in Q, so that at instance we have 'n' nodes in Q.

approach 2 :
have 2 pointers which point to head of linked list  say p1 and p2 . iterate p1 to 'n' positions from head pointer. then again iterate p1 and p2 together, until p1 reaches the end of linked list. now the positions of p1 and p2 will differ by n positions . the position of p2 will be at n positions from end .

as the approach 2 has less space complexity, I am going to give pseudo code for approach 2 :


pseudo code:


node GetLast_Nelements(node head, int n )
{
if (head==NULL)
return NULL


p1=p2=head


for(i=0; i < n ; i=i+1)
{
  if(p1 ==NULL)
    return head ; //linked list doesnt have 'n' elements at all
  p1=p1->next
}


while (p1 !=NULL)
{
p1=p1->next;
p2=p2->next ;
}
return p1 ;
}


Q) swap elements in linked list 

input list : 1->2->3->4->5->6

output list: 2->1->4->3->6->5

A)
node * shuffle (node *&head)
{
if(head == NULL)
return head ;

if (head->next ==NULL)
return head;

node *firstnode=head;
node *secondnode=firstnode->next;


firstnode->next=firstnode->next->next ;
secondnode->next=firstnode;
head=secondnode ;
node *prev=firstnode;
firstnode=firstnode->next;

node *temp=NULL,*next=NULL,*curr=NULL;

while(firstnode !=NULL && firstnode->next!=NULL)
{
 curr=firstnode;
 temp=firstnode->next;
 firstnode->next=firstnode->next->next;

 prev->next=temp;
 temp->next=curr;
 prev=curr;

 firstnode=firstnode->next;
 }
prev->next=firstnode;
prev=firstnode;
return head ;
}


Q) merge linked lists in sorted way 

say we have 2 sorted linked lists to merge  n1 and n2 . Then pass head element of n1 , every element of n2  to the linkedListInsertSorted .


void linkedListInsertSorted( node** headReference,  node* newNode)
{
 // Special case for the head end

if (*headReference == NULL || (*headReference)->data >= newNode->data)

 {
newNode->next = *headReference;
*headReference = newNode;
}

else {

// Locate the node before which the insertion is to happen!

node* current = *headReference;
while (current->next!=NULL && current->next->data < newNode->data)
{
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
     }//end else
} // end func

C++ false sharing effect



Recently i had experienced performance bug due to false sharing in C++ product.

say that you have 2 processors each processor has its own cache memory .

imagine there are 2 threads . 1 thread is writing to a[10], other thread is just reading b[10].

okay, generally we imagine that when we read set of addresses very frequently, it will be in cache of processor that executes . but here these two arrays fall in one  CACHE LINE of processor. so when ever a[10] is being written by 1st thread, b[10] is flushed from cache and again being written into cache again .

This scenario is called false sharing , my solution to the problem is add enough padding to arrays so that these two arrays dont fall in one CACHE LINE. I added padding of 54 , so totally 64. 64 * 4 bytes wont come in one CACHE LINE. so that thread 2 can work on b[64] and b[64] will be in cache line.

now

thread 1 operates on
a[64].....

thread 2 operates on ....
b[64]....

impact  The performance gain for me is 3x for this solution. wasting few bytes for 3x performance gain is always convincing :)

permutations of string

I happen to see an movie where police inspector gets a jumbled word as clue , he writes all permutations
of string on paper. so I wrote an algorithm/python program so that it returns all permutations of given string. atleast now the police officer will save his time :) hehe just kidding .

here is the python program.

how to execute this ?
python ./permutations  "word"

'''
Created on Apr 29, 2012

@author: vedara
'''
import sys
if(len(sys.argv) < 2):
    print "enter ./permutations.py "
    exit(0)
 
s=str(sys.argv[1])
out=[]
s_len=len(s)
used=[]

 
def permute(in_s1,out,used,length,reclength):
    i=0
 
    if(reclength==length):
        output=""
        print(output.join(out))
         

    while i < length:
     
        if(used[i]):
            i=i+1
            continue
     
        out[reclength]=in_s1[i]
        used[i]=1
        permute(in_s1,out,used,length,reclength+1)
        used[i]=0    
        i=i+1
   
for i in s:
    out.append(i)
 
i=0

while i < len(s):
    used.append(0)
    i=i+1
   
permute(s,out,used,len(s),0)
out=[]
used=[]

email me if indentation of program changes...if indentation changes program wont compile in python.. 

example : python permutations.py hey

output:
 hey 
 hye
 ehy
 eyh
 yhe
 yeh

Python tips for Automation

Why python for Automation?
if we write shell scripts for automation, it wont work on windows. if we write batch scripts it wont work on Unix platforms. so lets choose language which is platform independent, fast and development time is less.
It is none other than Python :) . Python is used not only for Scripting. it is programming language can be used for GUI , sockets, scripting, web programming :) .

I have been automating many test cases for performance testing team . It saves 20 hours of time per week. Going in future , routine tasks will be automated using Python :) . no need of hiring testers to do routine tasks which keep repeating every week or every month .

common things we use while writing Python scripts for automation .

1) coping files from one location to other.
2) check whether file exists
3) check which OS it is
4) invoking shell script or other executable from Python script
5) reading the Configuration files which are of Windows Config files .INI format  like below
   [boot]
timeout=30
quick=yes


the Answers are below

1a) import shutil
      shutil.copy(src,dest)

2a) import os
       file="/tmp/file1.txt"
      os.access(file, os.F_OK)

3a)
   import sys
  print(sys.platform)

4a)
    import subprocess
   p=subprocess.Popen(command,shell=True)
        p.wait() '''waits until process is done '''

5a) 
here is the program called ConfigChanger.py which takes 2 files as command line args. 
invoke as  $python ./ConfigChanger  file1.INI file2.INI . This changes file1.INI according to file2.INI . the common attributes present in file2.INI will be moved to file1.INI and new attributes present in file1.INI will not be changed . its like set operations file1 n file2 in file1 and file1 - file2 in file1. 

import ConfigParser
import sys 

if(len(sys.argv) < 3):
    print "\n python ./NQSConfigParser.py "
config=ConfigParser.ConfigParser() # source file2.INI
config.read(sys.argv[2]);   

config1=ConfigParser.ConfigParser() # destination file1.INI
config1.read(sys.argv[1]); 


list_sections=[ ];
i=0
j=0
index=()
Source={}
Dest={}
#element=[ ];
key=" "
values=" "

sec=config.sections() # source
sec1=config1.sections() 
tmpfile="%s_tmp"%(sys.argv[1])
nqsconfig_tmp=open(tmpfile,"wb") #destination file
for section in sec1:
    
    Dest_items=config1.items(section)
    if section in sec:
        Source_items=config.items(section)
    print "\n[%s]" %section
    section_write="[%s]\n" %section
    nqsconfig_tmp.write(section_write)
    
    for f in Source_items:
        key=str(f[0]).upper()
        value=f[1::]
        values=" "
        for val in value:
            values = values + val
        
        if values.find(";")== -1:
            values= values+";"    
        Source[key]=values
        

    for f in Dest_items:
        key=str(f[0]).upper()
        value=f[1::]
        values=" "
        for val in value:
            values = values + val
            if values.find(";")== -1:
                values= values+";"
        Dest[key]=values
        if key in Source:
            attribute="%s = %s\n" %(key, Source[key])
            nqsconfig_tmp.write(attribute)
        else:
            attribute="%s = %s\n" %(key, Dest[key])
            nqsconfig_tmp.write(attribute)

Dest={}
Source={}
nqsconfig_tmp.close()

Solaris - IO benchmarking - vdbench

do you want to measure performance of disks on solaris ?. then we have excellent tool called vdbench.

Initially I used to write c++ program which read/writes chunks of data and measure the Input/Output using iostat command. then i came across called vdbench which simulates read/write on given partition of hard disk .


go to http://sourceforge.net/projects/vdbench/ to download the tool and unzip it. 


1) create a file of 100 MB . $mkfile 100m /benchmark/file1 
2)now lets generate read/writes on this file /benchmark/file1 which is mounted on partition you want to benchmark IO. 

there are example files that come with installation like example1, example2 etc. we can edit example1 file ,

*Example 1: Single run, one raw disk

*SD:    Storage Definition
*WD:    Workload Definition
*RD:    Run Definition
*
sd=sd1,lun=/benchmark/file1
wd=wd1,sd=sd1,xfersize=4194304,rdpct=50
rd=run1,wd=wd1,iorate=100,elapsed=10,interval=1

* lun specifies the file, rawdisks etc.
*rdpct means read percentage. here i gave rdpct=50 means read % is 50, write % is 50. 
*xfersize is 4194304 bytes which means vdbench generates 4 MB of load. 
*elapsed is how many samples we need . we get 10 samples here 

3) issue the command $ vdbench -f example1 
Apr 20, 2012  interval        i/o   MB/sec   bytes   read     resp     resp     resp    cpu%  cpu%
                             rate  1024**2     i/o    pct     time      max   stddev sys+usr   sys
07:25:53.061         1      92.00  1559.74 4194304  53.26   13.379   26.133    2.459     2.1   2.0
07:25:54.021         2     108.00  1831.00 4194304  50.00   12.848   16.296    1.704     2.5   2.3
07:25:55.019         3     114.00  1932.72 4194304  54.39   12.824   24.141    2.158     2.5   2.4
07:25:56.018         4      93.00  1576.69 4194304  46.24   12.893   27.468    2.312     2.1   2.0
07:25:57.017         5     103.00  1746.23 4194304  52.43   12.491   15.294    1.514     2.2   2.1
07:25:58.016         6     118.00  2000.53 4194304  43.22   13.324   30.540    2.848     2.7   2.5
07:25:59.018         7     103.00  1746.23 4194304  44.66   12.661   16.723    1.527     2.2   2.1
07:26:00.016         8     102.00  1729.27 4194304  44.12   12.657   15.030    1.419     2.2   2.1
07:26:01.016         9     116.00  1966.63 4194304  45.69   12.635   16.636    1.483     2.5   2.5
07:26:02.019        10      90.00  1525.83 4194304  47.78   12.499   14.357    1.419     1.9   1.8
07:26:02.026  avg_2-10     105.22  1783.90 4194304  47.62   12.770   30.540    1.908     2.3   2.2
07:26:02.489 Vdbench execution completed successfully

the last line avg_2-10 is avg of all samples.

for 4mb read/writes here the response time is 12 secs. cpu usage is 2.3%


BITS Pilani MS Dissertation experience


I went to BITS Pilani hyderabad campus, I had instructed by security guys who

told me room number for Viva attendance. I took 20 mins to locate the room :) as campus is very

big .

we need to fill attendance form, and will be given evaluation sheet from BITS

representative . we need to carry the sheet with us when we go for viva and handover to

professor. The BITS representative will collect the evaluation sheet given by your Supervisor + Additional examiner. so grade given by BITS faculty + grade given by your supervisor will be final result.

each student is assigned to a faculty member and time slot is arranged for each student.

Student need to carry his/her own laptop to give presentation (or demo if any ) as they cant trust

pendrive or CDs due to viruses.

my time slot was 11:30 am and faculty chamber number was given. so at 11:30 I went to
faculty room and met the Professor. I gave the context of my project and started presentation .

The professor raised few questions and I answered them . Luckily I
got a very cool professor who has good knowledge and expert in operating systems. so she
grapsed my project technical details easily.

After completing my presentation/viva, I gave demo about my project .

By 12:00 pm the process is over, and professor said that i can visit BITS campus and library. I just

roamed in campus for 1 hour and campus is awesome.

Again I took 15 mins to come out from huge campus :) .

Finally I completed my MS in 2012, which I started in 2010.

I Thank my guide Nathan Reynolds for his Ideas, my manager for giving me excellent grade

from his evaluation and finally my wife for not asking for outings when I was reading,

coding etc.

I thank my parents who funded for my 1st sem :) .

unwind callstack on Linux


// callstack.cpp
#define UNW_LOCAL_ONLY
#include < stdio.h > 
#include < libunwind.h > 

void show_backtrace(void) {
 unw_cursor_t cursor; unw_context_t uc;
 unw_word_t ip, sp;

 unw_getcontext(&uc);
 unw_init_local(&cursor, &uc);
        char buf[512];
 while( unw_step(&cursor) > 0) {
  // unw_get_reg(&cursor, UNW_REG_IP, &ip);//uncomment these if you want to print ip and sp pointers.
  // unw_get_reg(&cursor, UNW_REG_SP, &sp);
//  printf("ip = %lx, sp = %lx\n", (long) ip, (long) sp);
              unw_get_proc_name(&cursor,buf,sizeof(buf),NULL);
              printf("%s\n",buf);

 }
}


$ gcc callstack.cpp -m32 -lunwind

use this show_backtrace function in your code where ever exceptions come. you can print the callstack on console. 

unlock your iphone 3G or 3GS

There are many articles in internet about unlocking iphone 3G/3GS. many folks are trying various methods and corrupting their iphones. here is the method you can follow.


1 . Download iPhone OS 3.1.2 firmware (3G / 3GS) and save it into a folder.


Note: Make sure you download the correct firmware for your iPhone model. Otherwise, you can’t upgrade the iPhone OS.
2. Connect your iPhone via USB and launch iTunes


Note: I suggest not to use the docking for the jailbreak. Connect the USB cable directly with your iPhone.
3. Restore your iPhone with iPhone OS 3.1.2. For Windows, hold SHIFT key and click on the “Restore” button and select the firmware file (with .ipsw extension) you have just downloaded. For Mac, hold option key and click on the “Restore” button and select the firmware file (with .ipsw extension) to restore.
jailbreak-312-step1
4. If you’re not using official sim, your iPhone will not be recognized by iTunes after restoration. Don’t worry. It’s normal. You can then close iTunes and continues with the next step.

Jailbreaking with blackra1n

5. Go to blackra1n.com and download blackra1n. Both Windows and Mac versions are available. So, you should download the correct version that matches your OS.
6. After downloading, unzip the blackra1n.zip an copy to
C:\Program Files\Common Files\Apple\Apple Application Support.
7. Make sure your iPhone is still connected with your computer via USB. Launch blackra1n.

Note: if you get error "Cannot find ASL.dll" . download ASL.dll from http://download.155384.com/english/asl.dll.html and copy to C:\Program Files\Common Files\Apple\Apple Application Support
blackra1n-icon
8. Click “make it ra1n” to start the jailbreak.
blackra1n-make-it-ra1n
9. Once you click the button, the jailbreak process starts and it’ll take around 30 seconds to complete.
Blackra1n - Jailbreaking in Progress
10. Wait until you see the following message and your iPhone should be jailbroken after reboot.
blackra1n-complete
your iPhone should have been activated and jailbroken. Now lets Unlock it . 

Installing Cydia

Tip: Before proceeding, if you have WiFi connection, I suggest you to first enable it before continuing. This should speed up the download process of cydia.
11. Next, you’ll have to install Cydia. connect to WIFI and Tap on the “blackra1n” icon.
blackra1n-app-iphone
12. Tap on “Cydia” and then “Install” button to install Cydia. Just wait until the download and installation to complete.
blackra1n-cydia-3g

Unlocking iPhone 3G/3GS with Blacksn0w

Okay, with cydia installed, the whole jailbreak process is complete. But if you need to unlock your iPhone 3G/3GS to work with unofficial sim, launch blackra1n app again. Simply tap “sn0w” and then select “install” to kick off the unlocking process. Wait for a moment and your iPhone will be automatically unlocked.

Note: Jailbreaking and unlocking iphone will make warranty void, pls try this at  your risk .

Memory leaks - Linux , Windows , Solaris

Dtrace to find memory leaks - Solaris 10

The dbx and libumem utilities are pretty slow in finding leaks. in my experience I didnt get callstacks for memory  leaks.  so I used Dtrace tool which can print malloc/free callstacks and size to outputfile. From the output file we can extract malloc addresses which are not present in free ptr address. these addresses and callstacks will be memory leaked ones.

Step 1 ) use this dtrace script to print malloc/free statistics . usage is ./memleak.d pid  > output.txt

#!/usr/sbin/dtrace -s
#echo " usage ./memleak.d pid "
pid$1:libc.so.1:malloc:entry
{
        self->trace = 1;
        self->size = arg0;
}
pid$1:libc.so.1:malloc:return
/self->trace == 1/
{
        printf("Ptr=0x%p Size=%d", arg1, self->size);
        ustack();
        self->trace = 0;
        self->size = 0;
}

pid$1:libc.so.1:free:entry
{
        printf("Ptr=0x%p ", arg0);
}

for example if the process id is 1234 then
/memleak.d  1234 > output.txt

 step 2 )
copy this python script to showleaks.py and run  python ./showleaks.py output.txt 6 > leaks.txt 
output.txt is the output file  you got from dtrace 
6 is the depth of callstack. make sure your output.txt has minimum of callstack depth 6. 

#showleaks.py


import sys
import re

if (len(sys.argv) > 1 ):
    allocsfile = open(sys.argv[1],'r')
    allocs_lines=list(allocsfile.readlines())
    linenums=len(allocs_lines)
    i=0
    poin_size=" "
    ''' str1='12  66201                    malloc:return Ptr=0x10244cb30 Size=73' '''
    allocs_map={}
    stacks_map={}
    final_map={}
    depth=int(sys.argv[2])

    malloc_set=set(" ")
    free_set=set(" ")
    while i < linenums:
   
        malloc_match=re.search(r"malloc:return Ptr=\b0[xX][0-9a-fA-F]+\b Size=[0-9]*", allocs_lines[i])
        free_match=re.search(r"free:entry Ptr=\b0[xX][0-9a-fA-F]+\b",allocs_lines[i])
        if malloc_match:
            malloc_line=str(malloc_match.group())
            pos_ptr=malloc_line.find('=')
            ptr_address=str(malloc_line[pos_ptr+1:pos_ptr+12])
            malloc_set.add(ptr_address)
            allocs_map[ptr_address]=i # store ptr addr and line number
        elif free_match:
            free_line=str(free_match.group())
            pos_ptr=free_line.find('=')
            freeptr_address=str(free_line[pos_ptr+1::])  
            free_set.add(freeptr_address)
        i=i+1
else:
    print("usage: ./showleaks.py ")

leak_set=malloc_set - free_set


for i in leak_set:
        j=allocs_map[i]
        formatstr="malloc:return Ptr=%s Size=[0-9]*" % i
        malloc_match=re.search(formatstr,allocs_lines[j])
        if malloc_match:
            malloc_line=str(malloc_match.group())
            pos_ptr=malloc_line.find('=')
            rest_of_line=str(malloc_line[pos_ptr+1::])
            pos_Size=rest_of_line.find('=')
            Size = int(rest_of_line[pos_Size+1::])
            callstack=str(allocs_lines[j+1:j+depth])

            if callstack in stacks_map:
                value=stacks_map[callstack]
                stacks_map[callstack] = value + Size
            else:
                stacks_map[callstack] = Size

keys=stacks_map.keys()

for k in keys:
    print("leaked bytes: %d" %stacks_map[k])
    stacks=str(k)
    stacks1=stacks.split(r'\n')
    for sts in stacks1:
        print(sts)
   
print("\n DONE ")
   
   
   

for any queries, pls do post here. I will respond to it .