始终牢记:malloc后,一定记得memset,否则,隐藏的BUG折腾死人!
下面这段简单的程序,在create_node()函数中,malloc后,忘了memset,结果运行时出现如下错误.还好代码规模不大,gdb跟踪后发现了异常.如果在一个庞大的工程中,忘了memset,问题就不一定好找了
$ ./NodeMallocFree
key=the first element, value=Ala
key=t, value=same key but different value
段错误 (核心已转储)
NodeMallocFree.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RET_TRUE 0
#define RET_FALSE -1
struct node {
char *key;
char *value;
struct node *next;
};
static void free_node(struct node **p)
{
struct node *n = *p;
if(NULL == n)
return;
if(n->key)
free(n->key);
if(n->value)
free(n->value);
n->key = NULL;
n->value = NULL;
free(n);
n = NULL;
}
static int copy_node_content(char **dst, char *src)
{
int len;
if(*dst || NULL == src)
return RET_FALSE;
len = strlen(src);
*dst = malloc(len+1);
memset(*dst, 0, len+1);
strncpy(*dst, src, len);
return RET_TRUE;
}
static struct node * create_node(char *key, char *value)
{
struct node *n;
n = malloc(sizeof(struct node));
// Be careful !!!!!
//memset(n, 0, sizeof(struct node));
if(key)
copy_node_content(&n->key, key);
if(value)
copy_node_content(&n->value, value);
return n;
}
static void print_node(struct node *n)
{
printf("key=%s, value=%s\n", n->key, n->value);
}
int main()
{
struct node *n, *n2;
n = create_node("the first element", "Ala");
print_node(n);
free_node(&n);
n2 = create_node("the first element", "same key but different value");
print_node(n2);
free_node(&n2);
return 0;
}