c - C中的struct和free()
问题描述
每当我插入一个新值时,我的数据都会被覆盖,如果我在主程序中省略了我的 free(),我的程序工作正常。为什么?如何纠正这个问题。结构的内存分配是否正确?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct List
{
char val[20] ;
};
struct Hashtable
{
struct List *start;
};
struct Hashtable ht[26];
void init();
void insert(struct List*);
void init()
{
register int j;
for (j=0;j<26;j++)
{
ht[j].start=NULL;
}
}
int main(void)
{
init();
int i=0;
for (int i=0;i<5;i++)
{
struct List *newnode=(struct List*)malloc(sizeof(struct List));
scanf("%s",newnode->val);
insert(newnode);
free(newnode);
newnode=NULL;
}
return 0;
}
void insert(struct List *node)
{
if ( ht[node->val[0]-97].start==NULL)
{
ht[node->val[0]-97].start=node;
return;
}
else
{
printf("The value is %s\n", ht[node->val[0]-97].start->val);
}
}
-------------------------------------------------- -------------------------------------------------- --------------------------------------------- ___________________________________________________________________________
解决方案
当您分配指针时,您只复制指针本身,而不是它们可能指向的内存。
当您free
使用指针调用时,该指针的所有副本都将变为无效并且不能再使用。
您要么需要在函数中创建一个全新的副本insert
(包括分配新List
结构),要么不应该调用free
.
我个人的建议是您根本不在main
函数中进行分配,并且该insert
函数将字符串作为参数“插入”(而不是List
当前使用的指针)。
也许是这样的:
void insert(char *val)
{
// Get the hash-table index (note that it only works with ASCII encoding)
char hash = tolower(val[0]) - 'a';
// First check if it exists
if (ht[hash].start == NULL)
{
// No, then add it
// First allocate memory for the node
struct List *node = malloc(sizeof *node);
// Then copy the string
strcpy(node->val, val);
// And finally add it
ht[hash].start = node;
}
}
那么你在main
函数中的循环可能就像
for (unsigned i = 0; i < 5; ++i)
{
char val[20];
scanf("%19s", val);
insert(val);
}
推荐阅读
- javascript - 有一个检查许多项目的事件侦听器更好,还是让每个项目都有自己的侦听器?
- html - 如何使用 SASS/CSS 使 HTML 表格占满宽度
- reactjs - 如何将 es6 箭头函数参数替换为自定义类型(接口)?
- r - 安装 RStudio 后如何解决错误
- c# - 任务等待者
不实施 INotifyCompletion - bash - 存储 bash 脚本的输出以供重用
- ruby-on-rails - Rails SMTPAuthenticationError - 不接受用户名和密码
- java - 如何在spring boot中显示mysql视图?
- sql-server - 如何在 SQL Server/Azure 中不硬编码列名的情况下进行 PIVOT?
- google-calendar-api - 与域的所有用户共享模拟帐户的日历