开发者

Debug simple c code, double linked list copy

开发者 https://www.devze.com 2023-02-25 04:49 出处:网络
[my files are here(link removed)] My copy function doesn\'t copy the whole list. As required by @Mat, here is the \"copy\" function, but you still need to read the rest of the file to understand my

[my files are here(link removed)]

My copy function doesn't copy the whole list.

As required by @Mat, here is the "copy" function, but you still need to read the rest of the file to understand my struct.

Line copyLineText(Line l){
  Line newl = malloc (sizeof( struct node ));
  checkMalloc(ne开发者_如何学Cwl,"copyLineText");
  newl->length = l->length;
  newl->buffer = malloc((newl->length)* sizeof(char));
  checkMalloc(newl->buffer,"copyLineText buffer");
  strncpy(newl->buffer, l->buffer, newl->length);
  return newl;
}
/* Copy the lines between and including 'from' and 'to' of the textbuffer
 * 'tb'.
 *
 * - The result is a new textbuffer (much as one created with newTB()).
 * - The textbuffer 'tb' will remain unmodified.
 * - The program is to abort() with an error message if 'from' or 'to' is out
 *   of range. 
 */
TB copyTB (TB tb, int from, int to){
    if (from > to || from < 0 || to >= tb->numLines){
        printf("Error: the from to is out of range\n");
        abort();
    }
    Line line = tb->begin;
    while(line->linePosition != from){
        line = line->next;
    }

    TB tbCopy = malloc (sizeof( struct textbuffer ));

    Line last = NULL, curr = line, currCopy;

    while( curr != NULL && (curr->linePosition != to + 1) ){
        currCopy = copyLineText(curr);

        if(last == NULL){
          tbCopy->begin  = currCopy;
        }
        currCopy->prev = last;
        if(last != NULL){
            last->next = currCopy;
            //printf("362debug: last->next = currCopy\n");
        }
        last = curr;
        //printf("364debug: %d\n",curr->linePosition);
        curr = curr->next;
    }

        currCopy->next = NULL;
        tbCopy->end  = currCopy;
        tbCopy->numLines  = to - from + 1;
        return tbCopy;
}

If you run my code, you'll see:

tb2:2 lines
abcde
fg


tb2copy:2 lines
abcde

With this simple test, the copy produced by my function has one line less than the original structure.


On line 161 in question.c, while you're copying your linked list, you're assigning elements from the original linked list to last, instead of assigning the previous one from the newly created list.

Change that line from:

last = curr;

to:

last = currCopy;
0

精彩评论

暂无评论...
验证码 换一张
取 消