#!/bin/sh

# NOTE: "freeing unalloced mem" msgs are sent to stderr
#       (a questionable feature since the malloc library shd detect this) 

if test $# -ne 0; then
	echo "usage: mprlk" >&2
	exit 1
fi

awk -F: '
	/^m/ {	if ($NF)
			malloc[$NF]=sprintf("%d:%s", NR, $0) }

	/^f/ {	if ($NF && !malloc[$NF])
			printf "mprlk: %s (NR=%d)\n", $0, NR |"cat 1>&2"
		delete malloc[$NF] }

	/^r/ {	alloc=1
		if ($(NF-1) && !malloc[$(NF-1)]) {
			printf "mprlk: %s (NR=%d)\n", $0, NR |"cat 1>&2"
			alloc=0
		}
		delete malloc[$(NF-1)]
		if ($NF)
			malloc[$NF]=sprintf("%d:%s", NR, $0)
		else if ($(NF-2) && $(NF-1) && alloc)
			malloc[$(NF-1)]=sprintf("%d:%s\n", NR, $0) }

	END  {	for (i in malloc)
			print malloc[i] }' |

sort -n -t: | cut -d: -f2-

exit 0
