-1

Is this code correct?

int *set_new (int choice) {
   int *new_choice {new int};
   *new_choice = choice;
   return new_choice;
}

Should I delete *new_choice after the value is returned, because *new_choice is on the memory heap?

int *set_new (int choice) {
   int *new_choice {new int};
   *new_choice = choice;
   return new_choice;
   delete new_choice;
}

Or, do I need to delete it where the function is finished calling? if not deleted, will it cause a memory leak?

I learned on a website if you use dynamic memory (new) immediately after that delete (delete) so there is no memory leak.

The function is called in main:

int main () {
 int *b {new_choice (23)};
 printf ("% d", *b);
 delete b;
}
drescherjm
  • 8,907
  • 5
  • 42
  • 60
Sam Smith
  • 5
  • 2

2 Answers2

0

You must not delete what will be used. The pointer assigned to new_choice will be used by the caller of set_new, so you must not free that.

Also you cannot delete things after returning in the function to return because return means the execution of the function ends at that point and the execution returns to the caller.

int *set_new (int choice) {
   int *new_choice {new int};
   *new_choice = choice;
   return new_choice;
   delete new_choice; // this statement won't be reached
}
MikeCAT
  • 61,086
  • 10
  • 41
  • 58
0
int *set_new (int choice) {
   int *new_choice {new int};
   *new_choice = choice;
   return new_choice;
   delete new_choice;
}

The delete line will never be executed. Function ends with a return statement (among others). If you try to remove delete before return, it will be executed, but the pointer returned will be invalid, so it's pointless.

Your final example is correct, you should delete after you are done using the pointed-to object.

Yksisarvinen
  • 13,037
  • 1
  • 18
  • 42