这是我在 StackOverFlow 上的第一篇文章,我正在用 C 语言编写链表代码,突然发现一个我无法解决的情况(位于 dupstring 函数中)。这是我当前的代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <stdint.h>
typedef struct node
{
char * word;
struct node * next;
}node;
void add_node(node ** list, const char * word);
void print_linked_list(node * list);
char * dupstring(const char *s);
// MAIN
//___________________________________________
int main(void)
{
srand(time(0));
char buffer
node * linked_list;
add_node(&linked_list,"ola");
//add_node(&linked_list,"adeus");
return 0;
}
//____________________________________________
void add_node(node ** list, const char * word)
{
node * new_node = malloc(sizeof(node));
if(new_node == NULL)
{
printf("Error creating node");
free(new_node);
return;
}
char * temp_string = dupstring(word);
printf("%p", &temp_string);
printf("%s", temp_string);
new_node->word = temp_string;
free(temp_string);
new_node->next = *list;
*list = new_node;
}
void print_linked_list(node * list)
{
}
char * dupstring(const char * word)
{
uint32_t length = strlen(word);
char * copy = malloc(length + 1);
for (uint32_t i = 0; i < length + 1; ++i)
{
copy[i] = word[i];
}
return copy;
}
我的问题是,分配的每个内存都应该在某个时候释放,我为复制(动态字符串)分配了内存,但在返回之前我无法释放复制。有什么好的方法可以解决这个问题
我想不出一种方法,可以让我将 dupstring 的参数字保留为 const 变量。
希望任何人都可以提供帮助,我愿意接受任何类型的批评。 为大家加油。
对于初学者来说,您没有初始化指针
linked_list
node * linked_list;
你需要写
node * linked_list = NULL;
函数
add_node
不应输出任何消息。它应该向调用者报告是否成功。函数的调用者将决定是否输出消息。
所以最好像这样声明函数
int add_node( node **list, const char *word );
在这个 if 语句中
if(new_node == NULL)
{
printf("Error creating node");
free(new_node);
return;
}
free
的调用是多余的,因为指针new_node
已经等于NULL
。没有分配内存。
printf
的这个调用应该写成
printf("%p\n", ( void * )temp_string);
并且您需要检查是否为字符串分配了内存。那是在函数
dupstring
中,您需要检查调用malloc
的结果。该函数可以写成
char * dupstring( const char *word )
{
size_t length = strlen( word );
char *copy = malloc( length + 1 );
if ( copy != NULL ) strcpy( copy, word );
return copy;
}
您将分配的字符串的地址分配给指针
new_node->word
,并立即删除了该字符串。
new_node->word = temp_string;
free(temp_string);
所以指针的值无效。取消引用它会导致未定义的行为。
函数
add_node
可以如下所示
int add_node( node **list, const char *word )
{
char *temp_string = dupstring( word );
int success = temp_string != NULL;
if ( success )
{
node *new_node = malloc( sizeof( node ) );
success = new_node != NULL;
if ( success )
{
new_node->word = temp_string;
new_node->next = *list;
*list = new_node;
}
else
{
free( temp_string );
}
}
return success;
}
函数
print_linked_list
应该声明为
void print_linked_list( const node *list );