1 c memory-leaks structure linked-list
请考虑以下代码段
struct node {
char *name;
int m1;
struct node *next;
};
struct node* head = 0; //start with NULL list
void addRecord(const char *pName, int ms1)
{
struct node* newNode = (struct node*) malloc(sizeof(struct node)); // allocate node
int nameLength = tStrlen(pName);
newNode->name = (char *) malloc(nameLength);
tStrcpy(newNode->name, pName);
newNode->m1 = ms1;
newNode->next = head; // link the old list off the new node
head = newNode;
}
void clear(void)
{
struct node* current = head;
struct node* next;
while (current != 0)
{
next = current->next; // note the next pointer
/* if(current->name !=0)
{
free(current->name);
}
*/
if(current !=0 )
{
free(current); // delete the node
}
current = next; // advance to the next node
}
head = 0;
}
Run Code Online (Sandbox Code Playgroud)
问题:我无法释放当前 - >名称,只有当我评论释放名称时,程序才有效.如果我取消注释current-> name的免费部分,我的visual studio窗口中会出现Heap损坏错误.我怎么能免费提名?
答复:
@ all,YES,结构声明中有拼写错误.应该是char*name和struct node*next.看起来stackoverflow编辑器夺走了这两颗星.
通过执行malloc(nameLength + 1)解决了该问题.但是,如果我尝试在命令提示符下运行旧代码(malloc(namelength))而不是在visual studio上运行,它运行正常.看起来,某些编译器正在进行严格的检查.
我仍然不明白的一件事是,free不需要NULL终止指针,并且在这里覆盖分配指针的可能性非常小.
user2531639又名Neeraj
这是写入超出已分配内存的末尾,因为空终止字符没有空间,导致未定义的行为:
newNode->name = (char *) malloc(nameLength);
tStrcpy(newNode->name, pName);
Run Code Online (Sandbox Code Playgroud)
纠正:
newNode->name = malloc(nameLength + 1);
if (newNode->name)
{
tStrcpy(newNode->name, pName);
}
Run Code Online (Sandbox Code Playgroud)
注意free()使用NULL指针调用是安全的,因此NULL在调用它之前检查是多余的:
free(current->name);
free(current);
Run Code Online (Sandbox Code Playgroud)
另外,我假设在发布的struct定义中存在拼写错误(作为类型name和next应该是指针):
struct node {
char* name;
int m1;
struct node* next;
};
Run Code Online (Sandbox Code Playgroud)