0

I have the following code:

#include <iostream>

using namespace std;

void memoryAddr();
int *returnArray();

int main()
{
    memoryAddr();
    int *array = returnArray();

    for (size_t i = 0; i < 10; ++i)
    {
        cout << array[i] << endl;
    }

    return -1;
}

void memoryAddr()
{
    int array[10];

    for (size_t i = 0; i < 10; ++i)
    {
        array[i] = i;
    }

    int *aPtr = array;

    cout << "&array: " << &array << endl; // 0xffffcbc0
    cout << "&array[0]: " << &array[0] << endl; // 0xffffcbc0
    cout << "&aPtr: " << &aPtr << endl; // 0xffffcc00
}

int *returnArray()
{
    int array2[10];
    int *ptr2;

    for (size_t i = 0; i < 10; ++i)
    {
        array2[i] = i;
    }

    ptr2 = array2;

    return ptr2;
}

Question 1: When I run memoryAddr() I get the following memory addresses:

&array: 0xffffcb90
&array[0]: 0xffffcb90
&aPtr: 0xffffcbc0

Why is &aPtr different to the other two? Isn't it supposed to reference the memory address of the array?

Question 2: When a function returns something, do any pointers need to be freed up before it returns or does it automatically free up things when it returns? If they do need to be freed up does that include when the application terminates?

Question 3 When I run "returnAddr()" and I loop through the *array that the function returns it outputs undefined values. But if I specify it to access a certain element in the array such as *array[5] it will return what I expect it to return. Why does it work if I specify a index but returns strange values if I use a for loop?

user1157885
  • 1,999
  • 3
  • 23
  • 38
  • 1. `&aPtr` is a reference to a pointer to the array, not a reference to the array itself. 2. Pointers themselves don't need to be freed manually. If you allocated memory dynamically through the use of `new` or `malloc()`, then you need to free the memory by passing a pointer to it. –  Jan 21 '16 at 12:34
  • Inspecting the behaviors of undefined behavior doesn't make much sense. – πάντα ῥεῖ Jan 21 '16 at 12:34

0 Answers0