不要忽视任何细节---C语言链表操作的教训
最近发现服务器上一些服务进程一直处于长时间高CPU状态,有些进程甚至要跑10分钟左右,跟踪了一下发现,问题出现在如23-28代码中:
#include<stdio.h>#include<stdlib.h>#include<string.h>typedef struct NODE{ int nValue; struct NODE *ptNext;}Node;typedef struct LIST{ Node *ptLast; Node *ptList;}List;void Add2List(List **ptList, int nValue){ Node *ptNew = (Node *)calloc(1, sizeof(Node)); ptNew->nValue = nValue; if(NULL == *ptList) { (*ptList) = (List *)calloc(1, sizeof(List)); (*ptList)->ptLast = (*ptList)->ptList = ptNew; } else { (*ptList)->ptLast->ptNext = ptNew; (*ptList)->ptLast = ptNew; }}int main(){ List *ptList = NULL; Add2List(&ptList, 1); Add2List(&ptList, 2); return 0;}当然,以上的代码只是大概表现了添加链表元素的操作,如需要从链表中取出元素,也要根据每种方法的特殊性考虑各自的细节,特别是在多线程中,链表操作会变得更加复杂。