c - strcpy 损坏 char 数组(字符串值)

标签 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;
};

最佳答案

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

            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 结构,这样你就会得到未定义的行为),然后你就不会复制它。快速解决方法是在 malloc 之后执行 strcpy

您的realloc调用都是错误的。您不能使用 sizeof 来获取字符串的大小。为此,请使用 strlen,并且不要忘记为字符串终止符添加额外的字节。

此外,您不应分配firstsecond。它们是数据结构的迭代器。您要做的第一件事就是丢弃它们的值,这样就会泄漏内存。不要忘记之后释放您的temp结构以及temp->word

工作完成后,请停止所有这些 mallocstrcpy 业务!!!

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

哦,您是否还忘记从函数中返回一个值?

关于c - strcpy 损坏 char 数组(字符串值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650849/

相关文章:

c - 为什么即使在 C 中分配给大的可变长度数组也有固定值 -1?

c - 如何创建动态大小的结构数组?

c - 通过 epoll 使用多个文件描述符

c++ - 开发中如何避免 "swapping of death"?

c - malloc - 系统调用 - 它是如何制作的?

c - 在我用 C 实现的基本单链表中,Do-while 表现得很有趣。请指出错误

c - 如何理解链表中的双指针

java - Java中向循环双向链表添加节点

c - PostgreSQL:给定的带占位符的类型与 PQexecPrepared() paramValues 参数中的类型之间的关系

c - 将数组传递给函数 - 不同的值 - 段错误