How to reallocate memory anyhow, even if realloc() failed in c++

Viewed 324

After a successful allocation using malloc(), sometimes the program needs to increase the size of the array. Though malloc() worked successfully, but realloc() failed.

I've used this piece of code to handle the failure of realloc(). Here T is the template parameter. array is a pointer of type T, _size is the total index of the array has been already used, _maxSize is the maximum number of usable index. Reallocation is needed when _size reaches _maxSize.

if(_size == _maxSize){
    _maxSize *= 2;
    T *temp;
    temp = (T *) realloc( array, sizeof( T ) * (_maxSize) ) ;
    if(temp == NULL){
        printf("...reallocation of memory failed...\n");
        exit(0);
    }
    else{
        array = temp;
    }
}

Although the failure of realloc() was handled, the program really needs to increase the array size and I don't really know about how to perform the reallocation even if realloc() failed.

1 Answers

How to reallocate memory anyhow, even if realloc() failed in c++

In genuine C++, you never use malloc or realloc, just new (which is implemented in your C++ standard library implementation, and will call malloc internally!) and delete (it usually calls free), and preferably standard containers and smart pointers. Out of memory conditions are handled by exceptions (such as std::bad_alloc) and you could catch these exceptions.

In C, the robust solution would be to not use realloc and just use malloc, calloc, and free (with memset to clear the area, and memcpy to copy it).

The real issue is how to cleverly handle out-of-memory conditions. This is a design issue, and is application specific. Be aware of memoization and garbage collection techniques, concepts, and terminology. Observe that reference counting is a primitive, but often used in C++, garbage collection technique. So read the GC handbook or at least the tracing garbage collection wikipage for the concepts it will teach you.

Be aware of memory over-commitment. It is an OS feature that I dislike.

Be also aware that malloc and free (implemented in your C standard library implementation) are using operating system primitives (usually system calls). So read more about OSes, e.g. Operating Systems: Three Easy Pieces. On Linux, these OS primitives are (very often) mmap(2) and munmap(2). Because system calls are costly, your standard library will try to avoid them, and prefer marking free-d memory zones as reusable in future malloc-s.

Use valgrind to hunt memory leaks. You would prefer developing your C++ code on some Linux distribution just to have valgrind. My opinion is that Linux provides a very developer-friendly software environment, so I recommend Linux for most programmers and students. Don't forget to compile with g++ -Wall -g (maybe also -O2, when benchmarking) and use when needed the address sanitizer.

More generally, read http://norvig.com/21-days.html - it gives a wonderful insight.

Related