Memory Leaks: Tips for finding them?

I have been teaching myself c++ since UE4 came out and I feel I am now somewhat proficient in that I can now compile code successfully and it usually does what I expect it to. However, I now suspect I have one or more memory leaks in my functions that are called from tick. I let my game run for about 1 minute and then Unreal 4 dies. However, there in task manager the memory used by UE4 barely increases, only does spurts every now and then, and also decreases at times… So I am asking if this sounds like a memory leak and if there are any tips for detecting these besides commenting and uncommenting lines one by one?

I am also wondering in what instances delete ] pointer is appropriate.

If a function accepts a pointer as a parameter, should that function also delete that pointer?

Typically you will want to use a tool specially designed for tracking memory leaks. I’ve used SmartHeap, TotalView, and Valgrind.

You can’t go by memory size in the task manager, because the C++ memory manager is requesting large blocks and suballocating as it sees fit.

You would use delete] whenever you allocated an array of objects via new]

Typically functions would not delete a pointer passed in, this would not be best practice since the caller will very likely try to continue to use it.

You should learn about smart pointers in C++, for example here http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf
Once you will start using smart pointers, questions like: should function delete pointer will not bother you :slight_smile:

UE4 has own implementation of std::unique_ptr and std::shared_ptr, look at TUniquePtr and TSharedPtr in the code.

To add my two cents, your issue sounds very similar to the one I was experiencing (random crashes after a minute or so).
It might be due to UE4’s garbage collection. If you use UE factories to spawn objects, you MUST decorate the pointer with UPROPERTY() to instruct the GC NOT to collect the instance to which the pointer is pointing.
UE4 GC does not care whether you still have active references to that instance somewhere.
i.e.

instead of:



// Character Stats
UMyClass* MyClassPointer;


Rather use:



// Character Stats
UPROPERTY()
UMyClass* MyClassPointer;


"It might be due to UE4’s garbage collection. If you use UE factories to spawn objects, you MUST decorate the pointer with UPROPERTY() to instruct the GC NOT to collect the instance to which the pointer is pointing. " THIS… Gonna try this. Thank you so much, this makes sense. Even if it doesn’t fix it, its still a crucial piece of info I had missed. Thank you all very much for the tips.

EDIT: Fixed one small memory leak and a big issue with GC. Thank you all very much.