Hi all.

I have detected something that I can't explain, and hope someone can help me.

I have 2 functions for allocating and de-allocating arrays:

char **c;

void allocate()
{
  char **c = new char*[1000];
  for(int i = 0; i < 1000; i++)
  {
    char *g = new char[10000];
    for(int j = 0; j < 10000; j++)
    {
      g[j] = 'k';
    }
    c[i] = g;
  }
}

void deallocate()
{
  for(int i = 0; i < 1000; i++)
  {
    delete [] c[i];
    c[i] = NULL;
  }
  delete c;
  c = NULL;
}

void test()
{
  cout<<"Start Memory: "<<getMemory()<<endl;
  cout<<"Start Time: "<<getTime()<<endl;
  allocate();
  deallocate();
  cout<<"End Memory: "<<getMemory()<<endl;
  cout<<"End Time: "<<getTime()<<endl;
}

So this code basically allocates and deallocates an array of char* and measures the time/memory it took.
I've tested this, and got the result that test() either takes very much time and memory (lets say 100) or it takes very few memory/time (lets say 2).

If I run this test a few times right after each other (without closing the program), the results are either very high or very low (randomly).

So my question is, why does the same code sometimes takes very long (with much memory) and sometime very quick (with very low memory usage)?

However, when I use malloc instead of new, the memory and time stays +- constant

I think that new and delete try and initialise/clear-up the memory that they allocate, so that might take some time. Although for a char it shouldn't have much overhead. You are allocating quite a few elements though. malloc and free just allocate the memory and leave it uninitialised.

Hope that's a start. Maybe someone else knows a little more?

well I know that the last delete statement you have should be an array deletion, as such:

delete[] c;

But other than that, I don't see any reason for the "weird" behavior. It might simply be that your implementation (compiler + libs + OS) has a more sophisticated or different heap than the malloc/free allocator.

thanks for your answer, my code behaves differently under windows and ubuntu. So it's probably something regarding OS memory management.

With Linux, when you allocate memory, the application requests heap memory from the OS using the sbrk() function (deep inside the allocator). When you delete the memory, the heap allocated to the application is not returned (normally) to the operating system. It will be reused on subsequent allocations. In Windows, usually when you allocate memory, it is pulled from the operating system (it isn't cached in the application heap), and when you delete memory, it is returned to the operating system instead of keeping it in the application's heap cache. This can result in longer new/delete times with Windows than in Unix/Linux systems, at least in theory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.