【问题标题】:double free or corruption (fasttop) error c双重免费或损坏(fasttop)错误c
【发布时间】: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


【解决方案1】:

我只检查您认为错误所在的部分,并且我看到您第一次获得令牌,并且在循环中永远不会获取另一个令牌。只需在 while 循环中获取另一个标记即可。

例如:

    /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

这个例子取自:https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2014-06-25
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多