Append in custom string class not working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Append in custom string class not working

Please refer code below. I have started to create a custom class for string having char* and int as data members Why append is resulting into empty string ? https://code.sololearn.com/ceEk1Do2oG00/?ref=app

14th Jan 2023, 8:08 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 Answers
+ 2
Ketan Lalcheta Yes. It may behave undefined.. I just tried to adjust. And thought you can find, that you copying wrong only.. you can adjust that. You are creating a new pointer then it will not point to the original pointer in the class. So returns "empty string". In that case : you can try this way, for allocating new size. line 54 to 65 : delete m_pBuffer; m_pBuffer = nullptr; //copy to current from temp m_pBuffer = new char[newLen + 1]; m_iLength = newLen; strncpy(m_pBuffer, temp, newLen + 1); delete temp; temp = nullptr;
14th Jan 2023, 12:58 PM
Jayakrishna 🇮🇳
+ 3
line 54 to 65 : //delete original memory //delete m_pBuffer; //m_pBuffer = nullptr; //copy to current from temp //char* m_pBuffer = new char[newLen + 1]; m_iLength = newLen; strncpy(m_pBuffer, temp, strlen(temp)); ////delete original delete temp; temp = nullptr; edit: should take care of memory size..
14th Jan 2023, 9:18 AM
Jayakrishna 🇮🇳
+ 1
Ketan Lalcheta use string, why torture yourself with char*, memory allocations and code clutter... it's c++. https://code.sololearn.com/cm2PMGIGB35T/?ref=app
14th Jan 2023, 9:42 AM
Bob_Li
Bob_Li - avatar
+ 1
Bob_Li i know that string is already there but this is just to understand memory and play with that. See how i got error and that makes me learn something
14th Jan 2023, 12:14 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Jayakrishna🇮🇳 thanks. Basically you suggest not to delete the original memory and only delete the temp allocation. I have a question like how this works. Original allocation was for 5 characters (ketan) and we try to copy 13 characters directly.. isnt it bad or Am i missing something here ?
14th Jan 2023, 12:16 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Oh my bad... thanks for suggesting. I got it now. I was allocating the new variable named m_pBuffer instead of setting allocation to current member variable.
14th Jan 2023, 8:17 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta 😁 see, it gets confusing, micro-managing stuff. That's why optimization trade-off in favor of simplicity is sometimes worthwhile.
14th Jan 2023, 11:21 PM
Bob_Li
Bob_Li - avatar