'Problem with the function returning a pointer c++

I call a function that returns a pointer twice when I want to read the results, the first one is overwritten with the second

int *ip1Array = new int[4]; 
int *ip2Array = new int[4];

ip1Array = ipSplit(4);
ip2Array = ipSplit(2);

int *ipSplit(int ip)
        {
            static int ipTab[4];

            for (int i = 0; i <= ip; i++) {
                ipTab[i] = ip
            }

            return ipTab;
        }

This is just a piece of code in a very simplified sense. The problem is that the result of the first function call is overwritten by its second call. How to fix it?



Solution 1:[1]

int *ip1Array = new int[4]; 

This defines a pointer. You've initialised it to point to a dynamic array.

ip1Array = ipSplit(4);

This assignment overwrites the previous pointer value. Since that previous value was the only pointer to the dynamic array, nothing points to it anymore, and it can no longer be deleted. This is called a memory leak. Don't do this.


static int ipTab[4];

static means that the variable is same across all invocations of the function. Every call to the function will return a pointer to (first element of) the same array.

ip1Array = ipSplit(4);
ip2Array = ipSplit(2);

Both of these arrays point to the (first element of) same array that is returned by the function. And both of the dynamic arrays have leaked.


ip1Array = ipSplit(4);

You call the function with argument 4.

static int ipTab[4];

The array has 4 elements.

for (int i = 0; i <= ip; i++) {

You access through the indices 0,1,2,3,4. Count them. You access 5 different indices. You access outside the bounds of the array, and the behaviour of the program is undefined. Don't do this.


How to fix it?

  • Don't use owning bare pointers.
  • Don't access arrays outside of their bounds.
  • If don't want all arrays to be the same, then don't use static.

Since the sizes of the arrays are constant and small, you could use std::array:

auto
ipSplit(int ip)
{
    assert(ip <= 4);
    std::array<int, 5> ipTab{};
    for (int i = 0; i <= ip; i++) {
        ipTab[i] = ip
    }
    return ipTab;
}

// usage
auto ip1Array = ipSplit(4);
auto ip2Array = ipSplit(2);

Solution 2:[2]

It isn't overwritten, both pointers point to the same thing :

static int ipTab[4];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vlad Feinstein