Results 1 to 3 of 3

Thread: dynamic memory problems

  1. #1

    Thread Starter
    Hyperactive Member voidflux's Avatar
    Join Date
    Jun 2003
    Location
    Brockway, PA
    Posts
    290

    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.


    C¤ry Sanchez
    Computer Science/Engineering
    @ Penn State
    IBM.zSeries Intern
    Mandriva 2007

  2. #2
    Fanatic Member
    Join Date
    Dec 2003
    Posts
    703
    from a quick look, you don't seem to be updating your temp pointer, so you're copying to the same location every time.
    an ending

  3. #3

    Thread Starter
    Hyperactive Member voidflux's Avatar
    Join Date
    Jun 2003
    Location
    Brockway, PA
    Posts
    290
    Yes you are correct, I fixed that error and it still doesn't work, now its getting a null exception, any idea's?
    C¤ry Sanchez
    Computer Science/Engineering
    @ Penn State
    IBM.zSeries Intern
    Mandriva 2007

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width