我对 LinkedList 的经验很少,无法弄清楚测试字符串是否位于其中一个节点的逻辑。该程序总体上等待客户端发送 DNS 查询,然后以无限循环发回响应。我想做的是:
确定 LinkedList 是否具有客户端请求的主机名。如果不存在,请将其添加到 LinkedList 中,并在执行查找后将答案保存到同一节点。如果存在,只需向客户提供我已经查找并存储在 answer[]
中的答案即可。
这是一段简化的代码:
struct queryCache {
char* hostName;
uint8_t answer[UDP_RECV_SIZE];
struct queryCache* next;
};
struct queryCache* qcRoot;
int main (int argc, char** argv) {
// ...unrelated code
qcRoot = malloc(sizeof(struct queryCache));
qcRoot->hostName = 0;
qcRoot->next = 0;
while (1) {
// Wait for client with recvfrom()
char* cqHostName;
// Code that malloc()s and strcpy()s the client hostname into cqHostName
// Determine if cqHostName is in the cache
int hostNameInCache = 0;
struct queryCache* currQC = qcRoot;
while (currQC) {
if (!strcmp(currQC->hostName, cqHostName)) {
puts("In the cache");
hostNameInCache = 1;
break;
}
currQC = currQC->next;
}
// If cqHostName is not in the cache add its name
if (!hostNameInCache) {
currQC->hostName = malloc(strlen(cqHostName)+1);
strcpy(currQC->hostName, cqHostName);
printf("Added HOSTNAME: %s to the cache\n", cqHostName);
currQC->next = malloc(sizeof(struct queryCache));
currQC = currQC->next;
currQC->hostName = 0;
currQC->next = 0;
}
// Code that does a recursive DNS
// Code that will copy the response into the appropriate answer[] of the LinkedList
}
}
该程序似乎只是在第一个客户端请求后退出,而没有给出错误。如果我删除 LinkedList 代码,它就可以正常工作,所以我很确定出了什么问题与我检查字符串是否在 LinkedList 中的方式有关。
最佳答案
当hostNameInCache
为0时,currQC
很可能为NULL
,因此您无法推迟它。
将 while 循环的条件更改为
#------------v
while (currQC->next) {
if (!strcmp(currQC->hostName, cqHostName)) {
puts("In the cache");
hostNameInCache = 1;
break;
}
currQC = currQC->next;
}
关于c - 测试 LinkedList 中是否存在字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19535019/