So I have the following implementation of linked list:

#ifndef LINKED_LIST
#define LINKED_LIST

struct Student
{
	char* name;
	char* surrname;
	char* signin_number;
	char* grade;
	char* date;

	struct Student* next;
};

struct Student* begin = NULL;

void push_back(struct Student* student)
{
    struct Student* temp = NULL;

    if(begin == NULL)
    {
        begin = student;
        begin->next = NULL;
    }
    else
    {
        temp = begin;

        while( temp->next != NULL )
           temp = temp->next;

        student->next = NULL;
        temp->next = student;
    }
}

void clear()
{
    struct Student* temp = NULL;
    if (!begin) return;

    while(begin)
    {
        temp = begin->next;
        free(begin->name);
        free(begin->surrname);
        free(begin->signin_number);
        free(begin->date);
        free(begin->grade);
        free(begin);
        begin = temp;
    }
}

void print()
{
    struct Student* ptr = begin;

    while(ptr != NULL)
    {
        printf("%s\n", (*ptr).name);
		printf("%s\n", ptr->surrname);
		printf("%s\n", ptr->signin_number);
		printf("%s\n", ptr->date);
		printf("%s\n", ptr->grade);
        ptr = ptr->next;
    }
}

#endif

But the clear function does not work ... how should I free malloced memory?

I should also mention that I allocate members of structure like this ... the error might be here ...

struct Student* new_student;
        if((new_student = (struct Student*)malloc(sizeof(struct Student))) != NULL)
        {
            new_student->name = (char *)malloc(8 * sizeof(char));
			new_student->name = "Michael\0";
			new_student->surrname = (char *)malloc(8 * sizeof(char));
			new_student->surrname = "Douglas\0";
			new_student->signin_number = (char *)malloc(9 * sizeof(char));
			new_student->signin_number = "E1006951\0";
			new_student->grade = (char *)malloc(3 * sizeof(char));
			new_student->grade = "10\0";
			new_student->date = (char *)malloc(7 * sizeof(char));
			new_student->date = "262988\0";
            push_back(new_student);
        }

>the error might be here ...
It might.

>new_student->name = (char *)malloc(8 * sizeof(char));
You allocate memory to name, all is well so far (barring minor nits).

>new_student->name = "Michael\0";
Bzzt! You've now overwritten your only reference to the memory just allocated. Not only is this a memory leak, if you call free on a pointer that wasn't returned by malloc and friends, bad things happen. You probably want to use strcpy to copy the contents of that string literal into name.

It should go without saying that this bug is repeated several times and you should address each instance rather than just name. I used name as the example.

Thank you Narue for quick response! Program is working now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.