下面的函数尝试按升序对链接列表中的字符串进行排序。当它返回新列表时,它就会被损坏。
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->word
是 NULL
,它第一次应该是(请注意,您实际上并没有清除 temp
结构,这样你就会得到未定义的行为),然后你就不会复制它。快速解决方法是在 malloc
之后执行 strcpy
。
您的realloc
调用都是错误的。您不能使用 sizeof
来获取字符串的大小。为此,请使用 strlen
,并且不要忘记为字符串终止符添加额外的字节。
此外,您不应分配first
和second
。它们是数据结构的迭代器。您要做的第一件事就是丢弃它们的值,这样就会泄漏内存。不要忘记之后释放
您的temp
结构以及temp->word
。
工作完成后,请停止所有这些 malloc
和 strcpy
业务!!!
要移动字符串,只需移动指针即可。无需重新分配或复制。这会将您的代码简化为几行。
哦,您是否还忘记从函数中返回
一个值?
关于c - strcpy 损坏 char 数组(字符串值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650849/