View the step-by-step solution to:

Question

Hello, guys.


Can someone tell me what I''m doing wrong here? I'm facing a memory error when I

try to run this function.


  /*

  A set function that generically works with cstring pointer copying w/ dynamic memory

  A src and dest are given as parameters where the latter is a pointer reference. Where

 the dynamic allocation would take place.

  If the src isn't nullptr, normal processing occurs otherwise dest is set to nullptr.

  Assumes dest is allocated or has been set to a safe empty state / nullptr.

 The max_len dicates how much memory is to be allocated to the dest at maximum

 for the copying / the max number of characters to copy. It is nullbyte non inclusive.

  */


  void copystr(char*& dest, const char* src, unsigned int max_len) {

    

   delete[] dest;

   dest = '';


   if (src == '') {

     dest = nullptr;

   }

   if (strlen(src) > max_len) {

     dest = new char[max_len + 1];

   }

   else {

     dest = new char[strlen(src) + 1];

   }


   strcpy(dest, src);


  }

Top Answer

Sign up to view the full answer

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question