# V701. Possible realloc() leak: when realloc() fails to allocate memory, original pointer is lost. Consider assigning realloc() to a temporary pointer.

The analyzer has detected an expression of the 'foo = realloc(foo, ...)' pattern. This expression is potentially dangerous: it is recommended to save the result of the realloc function into a different variable.

The realloc(ptr, ...) function is used to change the size of some memory block. When it succeeds to do so without moving the data, the resulting pointer will coincide with the source ptr. When changing a memory block's size is impossible without moving it, the function will return the pointer to the new block while the old one will be freed. But when changing a memory block's size is currently impossible at all even with moving it, the function will return a null pointer. This situation may occur when allocating a large data array whose size is comparable to RAM size, and also when the memory is highly segmented. This third scenario is just what makes it potentially dangerous: if realloc(ptr, ...) returns a null pointer, the data block at the ptr address won't change in size. The main problem is that using a construct of the "ptr = realloc(ptr, ...)" pattern may cause losing the ptr pointer to this data block.

For example, see the following incorrect code taken from a real-life application:

    void buffer::resize(unsigned int newSize)
    {
      if (capacity < newSize)
      {
        capacity = newSize;
        ptr = (unsigned char *)realloc(ptr, capacity);
      }
    }

The realloc(...) function changes the buffer size when the required buffer size is larger than the current one. But what will happen if realloc() fails to allocate memory? It will result in writing NULL into ptr, which by itself is enough to cause a lot of troubles, but more than that, the pointer to the source memory area will be lost. The correct code looks as follows:

    void buffer::resize(unsigned int newSize)
    {
      if (capacity < newSize)
      {
        capacity = newSize;
        unsigned char * tmp = (unsigned char *)realloc(ptr, capacity);
        if (tmp == NULL)
        {
          /* Handle exception; maybe throw something */
        } else
          ptr = tmp;
      }
    }

This diagnostic is classified as:

CWE-401 CERT-MEM51-CPP CERT-WIN30-C

You can look at examples of errors detected by the V701 diagnostic.