Screenplay: C++: Dynamic Memory

C: malloc()/free()

TEST(MallocFree, ArrayOfInteger)
{
    int* ip = (int*)malloc(28*sizeof(int));
    ip[0] = 42;
    ip[27] = 7;
    free(ip);
}

Discussion

  • man malloc

    void *malloc(size_t size);
    
  • void*

  • C++ does not permit implicit conversion (which is good). Fix with cast.

valgrind: Memory Leak

Note

Make sure debug build is enabled.

TEST(Bug, MemoryLeak)
{
    int* ip = (int*)malloc(sizeof(int));
}
$ valgrind ./c++-dynamic-memory
$ valgrind --leak-check=full ./c++-dynamic-memory

valgrind: Array Bounds Write

TEST(Bug, ArrayBoundsWrite)
{
    int* ip = (int*)malloc(28*sizeof(int));
    ip[0] = 42;
    ip[27] = 7;
    ip[28] = 666;
    free(ip);
}
$ valgrind ./c++-dynamic-memory Bug.ArrayBoundsWrite

C++: new, delete

TEST(NewDelete, SingleInteger)
{
    int* ip = new int;
    *ip = 666;
    delete ip;
}

Discussion

  • new is typed

  • valgrind: leaks and bounds write/read detected just as well

C++: new, delete on Arrays

TEST(NewDelete, ArrayOfInteger)
{
    int* ip = new int[28];
    ip[0] = 42;
    ip[27] = 7;
    delete[] ip;
}

Discussion

  • Array delete!

valgrind: delete Mismatch

TEST(Bug, DeleteMismatch)
{
    int* ip = new int[28];
    delete ip;
}
$ valgrind ./c++-dynamic-memory Bug.DeleteMismatch