Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing character pointers into a function and dynamically allocating memory

Student.h

class Student
{
 private:
      char m_sHouse[64];
 public:
 Student(void);
 ~Student(void);
 void getHouse(char *hName);
 void setHouse(char *hName);
}

Student.cpp

 void Student::setHouse(char *hName)
 {
    strcpy(m_sHouse, hName);
 }

 void Student::getHouse(char *hName)
 {
     if (m_sHouse != NULL)
     {
        hName = new char[strlen(m_sHouse)+1];
        strcpy(hName, m_sHouse);
     }
 }

In main:

 student.getHouse(house);
 if (strcmp(house, "house") == 0)
     cout <<"\tCorrectly returned the student house: " << house<< endl;

setHouse(char *hName) sets student->m_sHouse equal to "house".

My question:

When inside getHouse(char *hName), it acts as it should, setting hName to "house". but when control is passed out of the function, my dynamically allocated memory is deallocated, so when I strcmp in main, my program crashes (I end up comparing a NULL pointer).

like image 579
Nick Avatar asked Mar 04 '26 18:03

Nick


1 Answers

Nick, the proper solution is that you know that hName is already allocated by the user of the class (Dr. Coleman). You simply need to strcpy into the character array.

Simply put:

void Student::getHouse(char *hName)
{
  strcpy(hName, m_sHouse);
}
like image 146
Drise Avatar answered Mar 06 '26 07:03

Drise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!