Skip to content

Instantly share code, notes, and snippets.

Prevention of memory leaks

In C++ the programmer is responsible for correctly allocating and releasing memory resources. Logical errors in the program can cause memory leaks, i.e. previously allocated memory is not being properly released after usage. The following guideline shows how to minimize the risk of accidentically leaking memory.

Do not dynamically allocate memory without reason

The obviously easiest way to avoid memory leaks, is to not dynamically allocate memory at all (i.e. using new or even malloc). More often than it should be, objects are dynamically allocated with new. This habit probably was carried over by Java programmers into the world of C++. Most of the time, however, in C++ it is sufficient to directly create objects on the stack:

MyClass obj(arg1, arg2);  // do this instead of MyClass *obj = new MyClass(arg1, arg2);
cmake_minimum_required( VERSION 3.0.2 )
find_package( Git )
message( "FindGit: ${GIT_EXECUTABLE}" )
file( GLOB_RECURSE CUSTOM_GIT_EXE "$ENV{LOCALAPPDATA}/GitHub/PortableGit_*/cmd/git.exe" )
message( "LocalAppData: $ENV{LOCALAPPDATA}" )
message( "GLOB_RECURSE: ${CUSTOM_GIT_EXE}" )

System specification:

  • Windows 7 64 Bit
  • Processor AMD Phenom(tm) II X4 945 Processor, 3000 Mhz, 4 Core(s), 4 Logical Processor(s)
  • 4GB RAM

Tested in Release mode:

Multithreading Benchmark RoR Version FPS
@mikadou
mikadou / func.cpp
Created December 18, 2015 10:38
Timestep floating point precision
float func(float dt)
{
float steps = dt * 2000.f;
return dt / steps;
}
@mikadou
mikadou / gist:99090107bfedf4785b90
Created December 16, 2015 15:24
Visualize error in timestep calculation
{
"metadata": {
"name": "",
"signature": "sha256:33e7f9e3f731a2024eada8fab72f28df081b12087b950267d15a973a3c2925f3"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [