Domanda

I'm very new to C++ (and studying Java). This is from HW but I think I've answered the HW issue and I'm just trying to get a better sense of pointers.

Say I have the following method:

int cubed(int a) {
  int * ptr;
  *ptr = a * a * a;
  return *ptr;
}

This compiles and works fine with the following:

int test = cubed(3);

I'm trying to get a sense of why it's bad to return a dereferenced pointer.

This question says that memory leak is a problem but I'm not sure why. Maybe because I don't understand what happens to a dereferenced pointer.

Does the lvalue just hang around indefinitely at that point? Do you have to actually delete the pointer? Any insight would be appreciated.

È stato utile?

Soluzione

The question you read is different. Say you had this code:

int cubed(int a) {
  int* ptr = new int;
  *ptr = a * a * a;
  return *ptr;
}

Now, you'd be leaking the dynamically-allocated int, because you'd return a copy of it and never delete the original.

Your code is actually worse because, instead of allocating with new, you're simply writing through an uninitialised pointer to memory that is not yours. In effect, you're writing to an int that does not exist.

What you should be doing is this:

constexpr int cubed(const int a)
{
   return a*a*a;
}

Or just invoke std::pow(value, 3) at the call site.

Altri suggerimenti

There is no memory link in your code, but there is another big bug.

You declare int * ptr; inside the function int cubed(int a), so it is a local variable.

The value of ptr will be random - might be NULL, might point to garbage, might point to some perfectly valid address. You don't initialize the variable ptr, so your code will sometimes crash.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top