【发布时间】:2017-11-12 02:54:44
【问题描述】:
我在下面的代码中收到双重免费或损坏 (fasttop)。似乎无法弄清楚哪个指针正在创建此错误。看起来错误是在 echo_cnt 函数的 while 循环中产生的。谢谢!
static void init_echo_cnt(void) {
sem_init(&mutex, 0, 1);
byte_cnt = 0;
}
void echo_cnt(int connfd) {
int n;
FILE *fp = fopen("words.txt", "r");
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, init_echo_cnt);
char *buf = calloc(MAXLINE, sizeof(char));
while((n=readLine(connfd, buf, MAXLINE)) != 0) {
char *str = fgets(buf, sizeof buf, fp);
char *token;
token = strtok(str, " ");
char *result = malloc(strlen(token +64));
while (token != NULL){
printf("In the while loop\n");
if (spellcheck(token, fp)==1){
strcat(result, token);
strcat(result, "OK");
}
else{
strcat(result, "MISPELLED");
}
ssize_t kick = write(connfd, result, MAXLINE);
free(result); }
}
close(connfd);
}
void *thread(void *vargp) {
int connfd;
pthread_detach(pthread_self());
printf("World\n");
while(1) {
connfd=sbuf_remove(sbuf); //remove socket
echo_cnt(connfd); //service client
}
close(connfd); //close socket
}
【问题讨论】:
-
由于
buf是一个指针,sizeof buf会给你指针的大小,而不是它指向的数据。既然您总是分配固定的编译时指定数量的内存,为什么不将buf设为一个数组呢?你也永远不会free分配给buf的内存,这会导致内存泄漏。 -
至于你的问题的可能原因,有两种选择:第一种是
strlen(token +64)没有给你token加64的长度,你做的基本上是通过@987654330 @ 作为指向strlen的指针。第二个可能的问题是malloc没有初始化它分配的内存,然后你使用strcat将该内存作为目标,这意味着strcat将遍历 indeterminate 内容以查找终止符(它可能根本找不到,或者超出分配内存的末尾)。 -
您可能想阅读以下内容:How to debug small programs
-
为了便于阅读和理解:1) 一致地缩进代码。在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格,而不是空格和制表符的混合。 2) 通过一个空行分隔代码块(for、if、else、while、do...while、switch、case、default)。
-
调用
write()时,获取返回值后,检查该值是否有错误等
标签: c multithreading sockets free corruption