basic_string::_M_construct null not valid
Всем привет! У меня возникла одна проблема при выполнении лабораторной работы, буду рад если поможете. Мне нужно создать функцию, которая удаляет элемент из начала списка, возвращая значение удаленного элемента. Для проверки работоспособности моей функции есть следующая проверка:
std::string alice = pop_front(first); //first->name = "Alice"
assert(!alice.empty());
При ее прохождении выдается следующая ошибка: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid и я не понимаю с чем она может быть связана.Буду рад любой помощи
Код функции:
std:: string pop_front(node_t *&head){
std:: string saved = head->name_;
delete head;
return saved;}
Структура списка:
struct node_t {
std::string name_;
node_t *next_{nullptr};};
UPD: полный код
main.cpp
#include "header.h"
#include <assert.h>
#include <iostream>
#include <stdio.h>
#include <string>
int main(int argc, char const *argv[], char *envp[])
{
node_t *first = NULL;
const char *data[3] = {"Alpha", "Bravo", "Charlie"};
for (unsigned int i = 0; i < 3; i++)
{
push_back(first, data[i]);
}
printf("%s\n", first->name_.c_str());
assert(3 == length(first));
node_t *charlie_ref = tail(first);
assert(charlie_ref->name_ == "Charlie");
push_front(first, "Alice");
assert(first->name_ == "Alice");
push_back(first, "Delta");
std::string delta = pop_back(first);
assert(delta == "Delta");
std::string alice = pop_front(first);
assert(!alice.empty());
clear(first);
}
header.h
#ifndef _HEADER_H_
#define _HEADER_H_
#include <string>
struct node_t
{
std::string name_;
node_t *next_{nullptr};
};
void clear(node_t *head);
node_t *tail(node_t *head);
unsigned int length(node_t *head);
void push_front(node_t *&list, const char *element);
void push_back(node_t *&head, const char *element);
std::string pop_front(node_t *&head);
std::string pop_back(node_t *&head);
#endif
header.cpp
#include "header.h"
#include <string>
void clear(node_t *head){
for (node_t * current = head; current; current = current->next_)
{
current = NULL;
}
}
node_t *tail(node_t *head){
while(head->next_){
head = head->next_;
}
return head;
}
unsigned int length(node_t *head){
int lenght = 0;
while(head){
lenght = lenght+1;
head = head->next_;
}
return lenght;
}
void push_front(node_t *&list, const char *element){
node_t *first = new node_t {element, list};
list = first;
}
void push_back(node_t *&head, const char *element) {
node_t *p = new node_t {element};
node_t *tmp = head;
if(head == nullptr){
head = p;
return;
}
while(tmp->next_){
tmp = tmp->next_;
}
tmp->next_ = p;
}
std:: string pop_front(node_t *&head){
std:: string saved = head->name_;
delete head;
return saved;
}
std::string pop_back(node_t *&head){
while(head->next_){
head = head->next_;
}
std::string saved = head->name_;
delete head;
return saved;
}}