如何释放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;
}