-1

I am not sure where is the dangling pointer here, i mean its an array not a pointer. it was in my exam and the answer was a dangling pointer? i am really confused i thought that a dangling pointer happens when a pointer is pointing outside and array scope ?

#include <iostream>
    using namespace std;

    int * f (int n) {
         int a[10];
         for (int i = 0; i < 10; i++)
              a[i] = i*n;
         return a;
    }

    void main() {
         int j, k;
         int * p;
         j = 12;
         p = f(j);
         for (k = 0; k < 10; k++) {
              cout << p[k];
         }
         cout << endl;
    }

1 Answers1

0

f() returns a pointer a, which is memory allocated locally in it (on the stack, actually), and "freed" when f() returns.

Accessing this memory later (in p = f(j)) actually accesses a dangling pointer.

In this specific case, I would change the code so f() will return a vector (which keeps it's data dynamically-allocated on the heap, and provides an array-like random access with the square-brackets operator):

#include <iostream>
#include <vector>

std::vector<int> f(int n)
{
    const size_t N = 10;
    std::vector<int> a(N);
    for (int i = 0; i < N; i++)
        a[i] = i*n;
    return a;
}

void main() {
    const int j = 12;
    std::vector<int> p = f(j);
    for (int k = 0; k < p.size(); k++) {
        std::cout << p[k];
    }
    std::cout << std::endl;
}

In the general case, when you'd like to return a pointer from a function, make sure to allocate the memory dynamically and return it in a way which lets the caller know it is responsible for releasing the memory. In short - return a std::unique_ptr.

uv_
  • 746
  • 2
  • 13
  • 25
  • how can i fix it? – kogmaw1337 Dec 15 '18 at 12:39
  • Good question! You should allocate it dynamically and pass its ownership outside. The modern way of doing this (if it was actually a pointer to a type, and not an array as in your case) would be to use std::unique_ptr, so the caller (main) would now it's responsible for releasing that memory. In your case, I would just use a vector and return it by value (since the actual data in the vector is handled dynamically, the compiler will probably return it without even making a copy). – uv_ Dec 15 '18 at 12:41
  • 1
    @kogmaw1337 _"how can i fix it?"_ Either use a `static` array in the function, or way better get used to `std::array` or `std::vector` classes you can simply return by value. – πάντα ῥεῖ Dec 15 '18 at 12:48