eos icon indicating copy to clipboard operation
eos copied to clipboard

memory leak in FunctionType::get

Open sunphy opened this issue 8 years ago • 2 comments

See here.

#include "Types.h"

#include <map>

namespace IR
{
	struct FunctionTypeMap
	{
		struct Key
		{
			ResultType ret;
			std::vector<ValueType> parameters;

			friend bool operator==(const Key& left,const Key& right) { return left.ret == right.ret && left.parameters == right.parameters; }
			friend bool operator!=(const Key& left,const Key& right) { return left.ret != right.ret || left.parameters != right.parameters; }
			friend bool operator<(const Key& left,const Key& right) { return left.ret < right.ret || (left.ret == right.ret && left.parameters < right.parameters); }
		};
		static std::map<Key,FunctionType*>& get()
		{
			static std::map<Key,FunctionType*> map;
			return map;
		}
	};

	template<typename Key,typename Value,typename CreateValueThunk>
	Value findExistingOrCreateNew(std::map<Key,Value>& map,Key&& key,CreateValueThunk createValueThunk)
	{
		auto mapIt = map.find(key);
		if(mapIt != map.end()) { return mapIt->second; }
		else
		{
			Value value = createValueThunk();
			map.insert({std::move(key),value});
			return value;
		}
	}

	const FunctionType* FunctionType::get(ResultType ret,const std::initializer_list<ValueType>& parameters)
	{ return findExistingOrCreateNew(FunctionTypeMap::get(),FunctionTypeMap::Key {ret,parameters},[=]{return new FunctionType(ret,parameters);}); }
	const FunctionType* FunctionType::get(ResultType ret,const std::vector<ValueType>& parameters)
	{ return findExistingOrCreateNew(FunctionTypeMap::get(),FunctionTypeMap::Key {ret,parameters},[=]{return new FunctionType(ret,parameters);}); }
	const FunctionType* FunctionType::get(ResultType ret)
	{ return findExistingOrCreateNew(FunctionTypeMap::get(),FunctionTypeMap::Key {ret,{}},[=]{return new FunctionType(ret,{});}); }
}

Every time add new FunctionType into map in findExistingOrCreateNew function, as least 32 bytes allocated, and not dealloc in future until nodeos terminate since map is a static variable.

sunphy avatar May 28 '18 10:05 sunphy

@bytemaster Any progress on this?

sunphy avatar May 30 '18 02:05 sunphy

This is not memory leak, as the number of different combinations of (Key,FunctionType) is already fixed at compile time.

taokayan avatar Jun 21 '18 07:06 taokayan