单链表加入节点,而且只是加到末尾,为什么总是不对?
struct link_list
{
struct sock_pipe_map *data;
struct link_list *next;
};
struct sock_pipe_map
{
unsigned int len;
char buf_recv[20];
}
head = (struct link_list *)malloc(sizeof(struct link_list));
head-> data = NULL;
head-> next = NULL;
struct link_list *
add_link(struct link_list *head, struct sock_pipe_map *map)
{
struct link_list *search1;
struct link_list *search2;
search1 = head;
while(search1-> next != NULL)
{
search1 = search1-> next;
}
if((search2 = (struct link_list *)malloc(sizeof(struct link_list)) )== NULL)
{
perror( "malloc error is ");
}
search2-> data = (struct sock_pipe_map *)malloc(sizeof(struct sock_pipe_map));
memset(search2-> data, 0, sizeof(struct sock_pipe_map));
memcpy(search2-> data, map, sizeof(struct sock_pipe_map));
printf( "after memcpy in add_link.\n ");
fflush(stdout);
search1-> next = search2;
search2 -> next = NULL;
return head;
}
[解决办法]
看着没什么问题,只有一点要注意:
没有对struct sock_pipe_map *map这个参数进行检查,如果该参数为NULL
这句可能会有问题的,memcpy(search2-> data, map, sizeof(struct sock_pipe_map))
[解决办法]
首先判断传入的指针是否为NULL
ASSERT(head == NULL);
ASSERT(map == NULL);
[解决办法]
if(head-> data == NULL)晕倒
而且head = search2; 不知道怎么想的,如果head就是专门的指针来就是
head-> next = search2
否则就该传**head