-
dynamic memory problems
Hello everyone, i'm implementing a string class and i'm having troubles understanding why my erase function displays garbadge.
My plan was to create a new dynamic array called temp which will hold the modified version of the array after the erase. I used memmove/memcopy from the <cstring> to store the new array.
here's my code:
note: memmove's function prototype is:
Code:
memmove(char * dest, const char *source, size_t count);
//count is how many bytes it should copy from source and move to destination.
note: chars is a dynamic array of type char so in the .h file it looks like:
Code:
private:
char *chars;
size_t allocated; //how many elements including the '\0'
size_t curr_len; //how many elements excluding the '\0'
Code:
void string::erase (size_t start, size_t count )
{
assert (start < length());
char *temp = new char [length()+1];
size_t counter = 0;
// Don't try to erase more chars than there are!
if (count > length() - start + 1)
count = length() - start + 1;
for(size_t i = 0; chars[i] != '\0'; i++)
{
if(i != start)
memmove(temp,chars+i,1);
//strcat(temp,chars[i]);
else if(i == start)
{
while(counter < count-1)
{
counter++;
++i;
}
}
}
The erase function will start deleting at the parm "start" and it will keep deleting until count is reach, so for example if you had:
[A][B][C][D]['\0']
0 1 2 3 4
erase(2,2);
it would start at C and delete C and D and you would be left with:
[A][B][\0']
Thanks.
:wave:
-
from a quick look, you don't seem to be updating your temp pointer, so you're copying to the same location every time.
-
Yes you are correct, I fixed that error and it still doesn't work, now its getting a null exception, any idea's?