Last Updated: February 25, 2016
·
387
· dawehner

Never trust memory

Today I had a fun experience with some of my code allocating a bunch of memory
and copy some data into it:

double* sendbuffer = new double[a * N];
// Copy over the local data to the prepared sendbuffer.
memcpy(sendbuffer + (b) * N, from, c * N * sizeof(double));

While this works pretty fine on systems with a lot of me memory it causes issues on system with not that much, given that sendbuffer might point to arbitrary bits in the RAM, and so can cause all kind of issues.

Ensure to memset for example before changing parts of the memory:

double* sendbuffer = new double[a * N];
    // Initialize the memory.
    memset(sendbuffer, 0, a * N * sizeof(double));
// Copy over the local data to the prepared sendbuffer.
memcpy(sendbuffer + (b) * N, from, c * N * sizeof(double));