strcpy破坏char数组(字符串值)

时间:2013-03-27 02:15:10

标签: c memory-management linked-list realloc strcpy

下面的函数尝试按升序对链表上的字符串进行排序。当它返回新列表时,它会被破坏。

void* order( void *ptr){
    struct wordlist *head;
    head = (struct wordlist *) ptr;

    struct wordlist *first = (struct wordlist*)malloc(sizeof(struct wordlist));
    struct wordlist *second = (struct wordlist*)malloc(sizeof(struct wordlist));
    struct wordlist *temp = (struct wordlist*)malloc(sizeof(struct wordlist));

    first = head;

    int j = 1;
    while( first != NULL){
        second = first->next;

        while( second != NULL){
            if( strcmp( first->word, second->word) > 0){
                if( temp->word == NULL){
                    temp->word = malloc( sizeof(first->word));
                }
                else{
                    if( realloc( temp->word, sizeof( first->word)) != NULL){
                        strcpy( temp->word, first->word);
                    }
                }

                if( realloc( first->word, sizeof(second->word)) != NULL){
                    strcpy( first->word, second->word);
                }

                if( realloc( second->word, sizeof(temp->word)) != NULL){
                    strcpy( second->word, temp->word);
                }

                free(temp);
            }
            second = second->next;
        }
        j++;
        first = first->next;
    }
}

例如,如果输入是

piero
ronaldo
messi

然后输出看起来像

messi
ŽŽŽ
ronaldo

上面的例子没有尝试代码,但它会给你一个线索。我相信内存分配有一些东西,但我无法找到它。顺便说一句,有时单词也会变空。

此外,词汇表如下:

struct wordlist{
    char *word;
    struct wordlist *next;
};

1 个答案:

答案 0 :(得分:1)

第一次不要将字符串复制到临时字符中。

            if( temp->word == NULL){
                temp->word = malloc( sizeof(first->word));
                // You forgot to copy!!
            }
            else{
                if( realloc( temp->word, sizeof( first->word)) != NULL){
                    strcpy( temp->word, first->word);
                }
            }

如果temp->wordNULL,请第一次应该(请注意,您实际上并没有清除temp结构已经你会得到未定义的行为),然后你不复制它。快速解决方法是在strcpy后执行malloc

您的realloc来电都错了。您无法使用sizeof来获取字符串的大小。请使用strlen,并且不要忘记为字符串终止符添加额外的字节。

此外,您不应该分配firstsecond。它们是数据结构的迭代器。你要做的第一件事就是抛弃它们的价值,以免泄漏记忆。不要忘记free temp结构以及之后的temp->word

在您开始工作之后,请停止所有mallocstrcpy业务!

要移动字符串,只需移动指针即可。无需重新分配或复制。这样可以将代码简化为几行。

哦,您是否也忘记了return来自您职能部门的价值?