0

Let's say i have this code.

int* Func(std::vector<int> integers)
{
   for (int i : integers)
   {
       if (something) 
       {
           return &i;
       }
   }

   return nullptr;
}

int* x = Func({3, 4, 5, 6, 7});
delete(x); ???

Should i delete 'x'(if it's not nullptr)? As far as i know we should only release memory allocated with the operator 'new'. This is certainly not the case here.

user361633
  • 203
  • 1
  • 11
  • 3
    You are returning a pointer to a local variable. This is undefined behaviour anyway, whether you delete or not. In general, you should not have functions returning raw pointers that the caller might have to delete. – juanchopanza Aug 11 '13 at 11:11
  • 1
    possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – chris Aug 11 '13 at 11:11

2 Answers2

2

Short answer: You are right that you shouldn't delete, but that's the least of your worries…

You are returning the address of a local variable (i). That's bad karma.

You could try to fix this as follows (note the two extra &s):

int * Func(std::vector<int> & integers) {
    for (int & i : integers)
        if (something)
            return &i;
    return nullptr;
}

But even then you have a problem, since the vector you're passing in is a temporary ({3, 4, …}) that gets destroyed before you go past the semicolon. In fact, I don't think it'll even compile, since we're now trying to pass a temporary as an l-value reference.

Since you're using C++11, here's what I think you're trying to accomplish:

std::vector<int> integers = {3, 4, 5, 6, 7};
auto x = std::find_if(begin(integers), end(integers), [](int i) { return something; });
if (x != end(integers)) {
    // Use *x…
} else {
    // Not found
}
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

You are correct that it should not be deleted since it wasn't newed but the biggest problem in your code snippet is that you are returning a pointer to the local variable i. This will mean that the pointer returned will have no defined meaning.

DrYap
  • 6,525
  • 2
  • 31
  • 54
  • What do you mean? if the condition in Func() is (i == 5) and then i have int* x = Func(...), 'x' will be 5. Note that i'm using gcc. – user361633 Aug 11 '13 at 11:26
  • 1
    `for (int i : integers)` creates the local variable `i` which may well be 5 but when you return from `Func` it goes out of scope so the memory it was stored in is no longer reserved for it so something else could overwrite it before you read it. – DrYap Aug 11 '13 at 11:31