+ 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
7 odpowiedzi
+ 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;
+ 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..
+ 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
+ 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
+ 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 ?
+ 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.
0
Ketan Lalcheta
😁 see, it gets confusing, micro-managing stuff.
That's why optimization trade-off in favor of simplicity is sometimes worthwhile.