I need to find lines of code after malloc that does not contain the word null, so that I can understand if the malloc was properly checked or not.
For example the following lines should be printed:
obj = (boolean *) malloc(DAYS_IN_WEEK * sizeof(boolean));
for(int i = 0; i < DAYS_IN_WEEK; i ){
This command partially works since it prints out the lines containing malloc
find . -type f -name '*.c' \( -exec grep -HnA2 'malloc' {} \;
should I add another grep? Not sure how to do it.
CodePudding user response:
There must be something easier but this seems close:
find . -name "*.c" -exec grep -nHA1 malloc {} \; |
awk '/^--/ {next} /malloc/{f=1; p=$0; next} f==1 && !/NULL/{f=0; print p; print $0}'
Explanation:
/^---/ {next}
ignores all lines starting with dashes thatgrep
generates/malloc/{f=1;p=$0;next}
sets a flagf
if the line containsmalloc
then remembers the line inp
and moves to the nextf=1...
checks if the flag is set (i.e. the previous line containedmalloc
) and the current line doesn't containNULL
, and if so, prints the previous and current lines