简体   繁体   中英

Trace Words in Shell Script

I am trying to find malloc-free series. Consider that we have 1000s of test cases. People may forget to free ptr. Please help me in optimizing the script.

Sample File Under test

Test(func_class,func1)
{
  int i,j;
  char* ptr = (char*) malloc(sizeof(char));
  free(ptr);
}

Test(func_class,func1)
{
  int i,j;
  char* ptr = (char*) malloc(sizeof(char));
  / Memory Leak / 
}

Script under development :

export MY_ROOT=`pwd`
_COUNT=0
pwd
_COUNT_WORD=0
filename=test.c
cat $filename | while read line
do 
    echo "Reading Line = $LINE" 
    for word in $line
    do
    _COUNT_WORD=$(($_COUNT_WORD+1))
    echo $_COUNT_WORD $word    
    if [ "$word" == "malloc\(sizeof\(char\)\);" ]; then    
        _MALLOC_FLAG=1   #this part of the code is not reached
        echo "Malloc Flag Hi"
        echo $word[2]
    fi
    done
    _COUNT_WORD=0
done 

I have some issue in matching the malloc regex. I know the script needs a lot of modifications as we have to find the pattern of individual person writing malloc.

There are other ways to check:

Using awk:

awk '/malloc/ || /free/{count++;}END{printf "%d",count}' fileundertest

This will search for "malloc" and "free" words in file and will print out the count. if count is even you can say for every malloc there is free.

Using grep:

grep -c "malloc" fileundertest 

This will count the malloc word in file

Similarly,

grep -c "free" fileundertest

To list out the line number

grep -n "malloc" fileundertest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM