+ 1

is assignment operator fine? [Resolved]

Hi Please find below code and let me know your view whether it is correct or not: https://code.sololearn.com/c28A15a163A2 Thank you for your help.

30th Apr 2021, 3:48 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 odpowiedzi
+ 3
Looks mostly good, but shouldn't you be allocating memory for strlen( ... ) + 1 characters in all your functions? You don't seem to be accounting for the null character that strcpy() copies as well, which would make it undefined behaviour.
30th Apr 2021, 4:52 PM
Shadow
Shadow - avatar
+ 2
Adding to Shadow's answer: Using the overload of constructor Student::Student() with no arguments results in a segmentation fault. This is because the statement on line 21 `Student(....);` has no effect. It simply creates a temporary object which gets destroyed at the end of the statetment. Your `m_chrName` and `m_chrLastName` properties are left uninitialized. So when the destructor is called, lines 47 and 52 attempt to deallocate memory pointed by these uninitialized properties, resulting in the segmentation fault. You will have to assign to the properties manually instead of calling another overload of the constructor. So the contents of Student::Student() would be ``` m_chrName = new char[2]{ 'A', 0 }; m_chrLastName = new char[2]{ 'B', 0 }; ```
30th Apr 2021, 5:49 PM
XXX
XXX - avatar
+ 2
XXX Heh, I didn't even catch that, nice one. I think it was probably intended to call the constructor from the initializer list, i.e. Student() : Student( ( char* ) "A", ( char* ) "B" ) {} This would be the correct way to call the overloaded constructor and have the intended effect, without manually assigning the values again.
30th Apr 2021, 6:10 PM
Shadow
Shadow - avatar
+ 2
Shadow you're right. That's a great way of not manually assigning properties. Although, `(char*) "A"` will need to be changed to `new char[2]{ 'A' }` as the memory is being manually deallocated in the destructor.
30th Apr 2021, 6:16 PM
XXX
XXX - avatar
+ 2
XXX Why that? The memory is already allocated in Student::Student( char*, char* ), where Student::Student() delegates to. Calling the constructor with a heap-allocated string would result in a memory leak, since no ownership is transferred.
30th Apr 2021, 6:44 PM
Shadow
Shadow - avatar
+ 2
Shadow oh right! In the back of mind, I was still thinking that the arguments were directly being assigned to the properties. You're right, no need of a heap allocated string.
30th Apr 2021, 8:24 PM
XXX
XXX - avatar
+ 1
Thank you so much for Shadow and XXX
30th Apr 2021, 8:54 PM
Ketan Lalcheta
Ketan Lalcheta - avatar