双重免费或腐败(快速顶部)错误c

时间:2017-11-12 02:54:44

标签: c multithreading sockets free corruption

我在下面的代码中收到了双重免费或损坏(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
    }

1 个答案:

答案 0 :(得分:0)

我只检查您认为错误的部分,我看到您第一次获得令牌,并且在循环中从不抓取另一个令牌。只需在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