C 释放由strdup分配的内存

C 释放由strdup分配的内存,c,free,strdup,C,Free,Strdup,如何释放strdup分配的内存? 我曾尝试在函数末尾使用free(linepos),但这会导致我的程序失败。我没有此函数之外的linepos,因此无法在其他任何地方释放它。先谢谢你 void putinqueue (queue *the_queue, FILE *input, char *filename) { char buffer[1024]; for (int linenr = 1; ; ++linenr) { char *linepos = fgets (buff

如何释放strdup分配的内存? 我曾尝试在函数末尾使用free(linepos),但这会导致我的程序失败。我没有此函数之外的linepos,因此无法在其他任何地方释放它。先谢谢你

void putinqueue (queue *the_queue, FILE *input, char *filename) {
   char buffer[1024];
   for (int linenr = 1; ; ++linenr) {
      char *linepos = fgets (buffer, sizeof buffer, input);
      if (linepos == NULL) break;
      linepos = strchr (buffer, '\n');
      if (linepos == NULL) {
         fflush (NULL);
         fprintf (stderr, "%s: %s[%d]: unterminated line\n",
                  execname, filename, linenr);
         fflush (NULL);
         exit_status = EXIT_FAILURE;
      }else {
         *linepos = '\0';
      }
      linepos = strdup (buffer);
      assert (linepos != NULL);
      insert_queue (the_queue, linepos);
   }
}
编辑:以下是其他功能。抱歉,复制并粘贴了旧源。这是新的

void insert_queue (queue *this, queue_item_t item) {
   //Inserts a new item at the end of queue.
   queue_node *temp = malloc(sizeof (struct queue_node));
   temp->item = item;
   temp->link = NULL;

   if (isempty_queue(this)) this->front = temp; 
   else this->rear->link = temp;
   this->rear = temp;
}

queue_item_t remove_queue (queue *this) {
   //This removes the first item from queue.
   assert (! isempty_queue (this));
   //Creates temp, and rVal and initializes them.
   queue_node *temp = this->front;
   queue_item_t rVal = temp->item;

   //Moves on to the next one.
   this->front = this->front->link;
   if (this->front == NULL) this->rear = NULL;
   //Free the unlinked node.
   free(temp);
   temp = NULL;
   return rVal;
}

“返回的指针可以传递到free()。您的问题更可能是关于
insert\u queue
正在做什么。如果它没有创建自己的副本,那么您正在释放队列仍在使用的内存(更应该由队列负责释放);显式删除队列时,应
释放内存。如果没有,您将不得不开始。队列项目是字符的typedef*吗?如果不是,您正在做什么?此行:
temp->item=item
表示队列确实使用了相同的内存位置。不要释放函数中的指针,而是只在使用完毕后才释放它;任何调用
remove\u queue
(即从队列中弹出项目)都负责在完成后释放内存。queue\u item\u t是char*的typedef,正确。