最近写了一个接受socket数据包,然后再重组上层协议包的东西。每次read到数据就将数据添加到一个链表的尾部,然后检查是否收到了一个完整的包。为了减少内存碎片,把用过的链表节点添加到另外一个链表中,这样下次可以从这个cache链表中重用节点。
在debug的时候我把cache list中的数据打印出来,代码如下:
struct seg_node { void* buf; unsigned int capacity; void* data; /* data >= buf, data is the position where available data begin with. */ unsigned int size; struct list_head list; };
struct my_pkg_reasm { struct list_head seg_list; struct list_head cache_list; unsigned int cur_total_size; };
void check_cache(struct my_pkg_reasm* reasm) { unsigned int count = 0; struct list_head* pos; printf("----------------cache list--------------------\n"); list_for_each(pos, &reasm->cache_list); { struct seg_node* node = list_entry(pos, struct seg_node, list); printf("capacity : %u, size : %u\n", node->capacity, node->size); } printf("-----------------------------------------------\n"); }
# define list_for_each(pos, head) for ((pos) = (head)->next; (pos) != (head); (pos) = (pos)->next) /* Iterate forward over the elements of the list. */ # define list_for_each_prev(pos, head) for (pos = (head)->prev; pos != (head); pos = pos->prev)检查了N遍,也没发现问题。那一刻,我竟然怀疑起linux系统了....... 于是,我默默地reboot了...
重启后,再去运行问题还是一样。
于是,我在cache_list的prev和next处加watchpoint,然后各种gdb调试,调试过程中并未发现内存被踩。当时真是无语了,果断不玩了,去打了局魔兽,然后吃了个冰激凌爽爽先。然后再来看看这个问题。这次仍然是GDB单步调试,只是这次更加仔细一些(平时本人比较马虎,看什么东西总是扫一眼,凭感觉),突然发现一个问题!!!!:
list_for_each(pos, &reasm->cache_list);那一刻,感觉像在路上捡到了一万块钱(捡到100块绝对不是那感觉)!!!有了这个分号,不管链表是不是空的,下面的代码都可以进去,而且正好节点前后的内存是可以访问的,所以没有发生段错误而是打印了一些奇怪的数据。
总结:怎么说呢,也不能说我是新手。这个问题怎么才能防止呢,我觉得一方面写代码时要细心,另外一方面,可以引进一个代码检查工具,像while for if之类的语句后面如果直接跟的分号,应该出一个告警。
原文:http://blog.csdn.net/joseph_1118/article/details/26968027